报错: Avoid mutating a prop directly since the value will be overwritten whenever the parent component........
原因: 所有的 prop 都使得其父子 prop 之间形成了一个单向下行绑定: 父级 prop 的更新会向下流动到子组件中, 但是反过来则不行.(父组件更新, 子组件中的 prop 值也会更新, 但子组件不能修改由父组件传递过来的值)
不能直接对父组件传来的值进行双向绑定, 要先子组件里定义新的变量来接收父组件传来的值, 接着我们可以使用 v-modal+watch 属性 或者 使用: binfd=""+ @input=" func"(再定义这个 func 通过传入的 event 得到改变的值, 将 event.target.value 赋值给新变量)
- <!DOCTYPE html>
- <HTML lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>
- Document
- </title>
- </head>
- <body>
- <div id="app">
- <h3>
- 我是父组件
- </h3>
- <templ :num-from-father="fatherData" :num-from-father2="fatherData2" @change1="changeFunc1"
- @change2="changeFunc2" />
- </div>
- <template id="temp">
- <div>
- <h3>
- 我是子组件
- </h3>
- <p>
- props1:{{numFromFather}}
- </p>
- <p>
- 转存的值:{{receiveNum1}}
- </p>
- <!-- 方法 1 -->
- <input type="number" :bind="receiveNum1" @input="receiveNum1Input">
- <p>
- props2:{{numFromFather2}}
- </p>
- <p>
- 转存的值:{{receiveNum2}}
- </p>
- <!-- 方法 2 使用 watch -->
- <input type="number" v-model="receiveNum2">
- </div>
- </template>
- <script src="/js/vue.js">
- </script>
- <script>
- const vm = new vue({
- el: '#app',
- data: {
- fatherData: 0,
- fatherData2: 10
- },
- methods: {
- changeFunc1(value) {
- this.fatherData = value * 1;
- },
- changeFunc2(value) {
- this.fatherData2 = value * 1;
- }
- },
- components: {
- templ: {
- template: '#temp',
- props: {
- numFromFather: Number,
- numFromFather2: Number,
- },
- data() {
- return {
- receiveNum1: this.numFromFather,
- receiveNum2: this.numFromFather2,
- }
- },
- methods: {
- receiveNum1Input(event) {
- this.receiveNum1 = event.target.value;
- this.$emit('change1', this.receiveNum1);
- this.receiveNum2 = this.receiveNum1 * 100;
- this.$emit('change2', this.receiveNum2);
- }
- },
- watch: {
- receiveNum2(newValue) {
- this.receiveNum2 = newValue;
- this.$emit('change2', this.receiveNum2);
- this.receiveNum1 = this.receiveNum2 / 100;
- this.$emit('change1', this.receiveNum1);
- }
- },
- }
- }
- })
- </script>
- </body>
- </HTML>
来源: http://www.bubuko.com/infodetail-3346598.html