-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
面试官:Vue中给对象添加新属性界面不刷新? #10
Comments
一、直接添加属性的问题我们从一个例子开始 定义一个 然后给 <p v-for="(value,key) in item" :key="key">
{{ value }}
</p>
<button @click="addProperty">动态添加新属性</button> 实例化一个 const app = new Vue({
el:"#app",
data:()=>{
item:{
oldProperty:"旧属性"
}
},
methods:{
addProperty(){
this.items.newProperty = "新属性" // 为items添加新属性
console.log(this.items) // 输出带有newProperty的items
}
}
}) 点击按钮,发现结果不及预期,数据虽然更新了( 二、原理分析为什么产生上面的情况呢? 下面来分析一下
const obj = {}
Object.defineProperty(obj, 'foo', {
get() {
console.log(`get foo:${val}`);
return val
},
set(newVal) {
if (newVal !== val) {
console.log(`set foo:${newVal}`);
val = newVal
}
}
})
} 当我们访问 obj.foo
obj.foo = 'new' 但是我们为 obj.bar = '新属性' 原因是一开始 三、解决方案
若想实现数据与视图同步更新,可采取下面三种解决方案:
Vue.set()Vue.set( target, propertyName/index, value ) 参数
返回值:设置的值 通过 关于 源码位置: function set (target: Array<any> | Object, key: any, val: any): any {
...
defineReactive(ob.value, key, val)
ob.dep.notify()
return val
} 这里无非再次调用 关于 大致代码如下: function defineReactive(obj, key, val) {
Object.defineProperty(obj, key, {
get() {
console.log(`get ${key}:${val}`);
return val
},
set(newVal) {
if (newVal !== val) {
console.log(`set ${key}:${newVal}`);
val = newVal
}
}
})
} Object.assign()直接使用 应创建一个新的对象,合并原对象和混入对象的属性 this.someObject = Object.assign({},this.someObject,{newProperty1:1,newProperty2:2 ...}) $forceUpdate如果你发现你自己需要在
PS:仅仅影响实例本身和插入插槽内容的子组件,而不是所有子组件。 小结
PS: 参考文献 |
实例代码错了
|
Vue3就没有这个问题了 |
No description provided.
The text was updated successfully, but these errors were encountered: