Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders.
不要直接修改父组件传递给子组件的props,可以使用基于props的一些变量或者计算属性来获得一些需要的数值
<body> <div id="app"> <div> 父组件 {{num1}} </div> <div> 子组件<com :num1="num1" @num1-change="num1Change"></com> </div> </div> <template id="com"> <input type="text" :value="num1" @input="num1Change($event)" /> </template> <script src="./vue.js"></script> <script> const com = { template: "#com", props: { num1: { type: Number } }, methods: { num1Change(e) { this.num1 = parseFloat(e.target.value) this.$emit('num1-change', this.num1) } } } new Vue({ el: "#app", data: { num1: 0 }, components: { com: com }, methods: { num1Change(num1) { this.num1 = num1 } } }) </script> |
报错如下:
[Vue warn]: 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: "num1" found in ---> <Com> <Root> warn @ vue.js:634 (anonymous) @ vue.js:4690 reactiveSetter @ vue.js:1060 proxySetter @ vue.js:4643 num1Change @ 64父子组建通信.html:34 input @ VM236:3 invokeWithErrorHandling @ vue.js:1872 invoker @ vue.js:2197 original._wrapper @ vue.js:7591 |
num1Change修改
num1Change(e) { this.$emit('num1-change', parseFloat(this.num1)) } |