uniapp如何赋值
数据绑定赋值
在uniapp中,可以通过数据绑定直接为变量赋值。在script部分的data中定义变量,模板中使用{{}}语法绑定值。
// script部分
data() {
return {
message: '初始值'
}
}
<!-- 模板部分 -->
<view>{{message}}</view>
通过方法修改message的值:
methods: {
updateMessage() {
this.message = '新值';
}
}
表单输入赋值
使用v-model实现表单元素与数据的双向绑定。
<input v-model="inputValue" />
data() {
return {
inputValue: ''
}
}
动态修改对象或数组
直接修改对象属性或数组元素可能无法触发视图更新,需使用this.$set或重新赋值整个对象/数组。

// 对象属性更新
this.$set(this.obj, 'key', 'value');
// 或
this.obj = { ...this.obj, key: 'value' };
// 数组元素更新
this.$set(this.arr, index, newValue);
// 或
this.arr.splice(index, 1, newValue);
通过事件传递赋值
父组件通过props传递数据给子组件,子组件通过事件修改父组件数据。
父组件:
<child-component :value="parentValue" @update="handleUpdate"></child-component>
methods: {
handleUpdate(newValue) {
this.parentValue = newValue;
}
}
子组件:

props: ['value'],
methods: {
emitUpdate() {
this.$emit('update', '新值');
}
}
全局变量赋值
在App.vue中定义全局变量,通过getApp().globalData访问。
// App.vue
globalData: {
globalVar: '全局值'
}
其他页面修改全局变量:
const app = getApp();
app.globalData.globalVar = '新全局值';
Storage本地存储赋值
使用uni.setStorageSync或uni.setStorage存储数据。
// 同步存储
uni.setStorageSync('key', 'value');
// 异步存储
uni.setStorage({
key: 'key',
data: 'value'
});





