-
关键代码:
// Child Component var TestComp = Vue.component('TestComp', { template: `<div>Child Component Prop Value : <br/> {{text}} </div>`, // child component prop --> text props: {text: {default: 'init prop'}} }); // Parent var vm = window.vm = new Vue({ el: "#root", template: "#app", mounted() { this.createSubComp(); }, data() {return {}}, methods: { createSubComp() { var that = this; var copy = Vue.extend(TestComp); var instance = window.vmsub = new copy({ // 是否取消注释 // 为何要设置parent: 当设置parent后, vue-devtools才能显示创建的vue实例 // parent: that }); instance.text = 'pass child component prop'; instance.$mount(); this.$el.append(instance.$el); } }, components: {TestComp} });
-
描述:
- 一个子组件:TestComp, 它有一个prop:text, 还有一个父组件, 在父组件中生成子组件实例
- 目前 parent: that是取消注释的, 这个时候, 设置子组件prop是可以的:
instance.text = 'pass sub component prop';
如果取消注释, 这个时候再执行, 就会报异常:
Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders,
Instead, use a data or computed property based on the prop's value. Prop being mutated: "text"
请问为何取消设置parent: that, 会对设置prop产生影响?
没设
parent
的时候,instance
就相当于是一个根实例,根实例中是可以直接修改props
的属性的