对象操作:三个参数:this.$set(“改变的对象”,“改变的对象属性”,“值”)
数组操作:三个参数:this.$set(“数组”,“下标”,“值”)
对数据整体进行操作:三个参数:this.$set(this,“要更新的数据名”,“更改的数据”)
代码示例:
<template>
<view class="hello">
<button @click="setMessage">添加属性</button>
{
{
student.name }}
<input type="text" v-model="student.age">
</view>
</template>
<script>
export default {
data() {
return {
student: {
name: '张三',
}
}
},
methods: {
setMessage() {
// this.student.age = 18 // 数据更新 视图不更新
// 1. 使用this.$set(obj, key, value) 强制更新
// this.$set(this.student, 'age', 18)
// 2. 通过Object.assign(target, sources)方法
// Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。
// Object.assign(target, …sources) 【target:目标对象】,【souce:源对象(可多个)】
this.student.age = 18
this.student = Object.assign({
}, this.student)
console.log(this.student)
}
}
}
</script>
<style>
</style>