一、先看代码
只因为写了这么一句代码,控制台就报警告了,先看看这段垃圾代码:
子组件:
this.$emit('update:height', data.height);
父组件:
<p-navbar title="商品列表" :height.sync="height"></p-navbar>
二、再看警告:
[Vue warn]: Avoid adding reactive properties to a Vue instance or its root $data at runtime - declare it upfront in the data option.
截图如下:
三、为什么会报警告
这个警告是 Vue.js 发出的,意思是你在 Vue 实例创建后的运行时动态地添加了响应式属性,这是不推荐的做法。在 Vue 中,你应该在 data 选项中预先声明所有的响应式属性。
例如,如果你在 created 或 mounted 钩子函数中添加了一个新的响应式属性,就可能会看到这个警告:
export default {
created() {
this.newProperty = 'Hello, world!';
}
}
为了避免这个警告,你应该在 data 选项中预先声明 newProperty:
export default {
data() {
return {
newProperty: null
};
},
created() {
this.newProperty = 'Hello, world!';
}
}
这样,Vue 就能在实例创建时追踪 newProperty 的变化,而不是在运行时动态地添加这个属性。这将提高性能并使状态更易于追踪。
四、最后我应该如何修改:
在 Vue.js 中,.sync 修饰符是一个语法糖,用于在子组件中更新父组件的属性。在你的代码中,你正在尝试更新父组件的 height 属性。
这个错误可能是因为你在父组件中没有预先声明 height 属性。你需要在父组件的 data 选项中声明 height 属性,如下所示:
export default {
data() {
return {
height: 0, // 初始值可以根据你的需要进行设置
};
},
}
然后,你可以在父组件的模板中使用 height 属性,并使用 .sync 修饰符来监听子组件的更新:
<p-navbar title="商品列表" :height.sync="height"></p-navbar>
在子组件中,你可以通过 $emit 方法触发一个 update:height 事件来更新 height 属性:
this.$emit('update:height', data.height);
这样,每当子组件触发 update:height 事件时,父组件的 height 属性就会被更新为传递的新值。