vue学习笔记6 父子组件的通信之 子组件修改由父组件传递过来的值 [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 pro

报错信息:

[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:

报错原因:

子组件不能修改父组件传递过来的值,props只能展示父组件传递过来的值,但不能修改。

解决办法:

用一个中介data参数传递。

解决步骤:

1 在子组件添加一个中介data属性

data(){
      return{
        dnumber1 : this.number1
      }
    },

2 在需要修改的地方使用这个data属性 而不是使用props属性

<!-- <input type="text" v-model='number1'> 不能用props属性值 会报错-->
         <input type="text" v-bind:value='dnumber1' @input='number1input'> 

3 编写input触发事件

methods:{
         number1input(event){
           //this.number1=event.target.value //不能直接修改
           this.dnumber1=event.target.value
           this.$emit('num1change',this.dnumber1)
         }
     },

4 编写发射接收函数 num1change

 methods:{
      num1change(value){
        //this.num1= value*1
        this.num1= parseInt(value)
      }
    },

5 向子组件传递此函数

<cpn v-bind:number1="num1"  @num1change="num1change" ></cpn>

完整源代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>New Web Project</title>
        <script src="vue.js"></script>
    </head>
    
    <body>
        <div id="app">
          <cpn v-bind:number1="num1"  @num1change="num1change" ></cpn>
        </div>
    </body>
    
  <!--子组件模板-->
  <template  id='cpn'>
    <div>
      <h2>props:{{number1}}</h2>
      <h2>data:{{dnumber1}}</h2>
      <h2>
        data:
        <!-- <input type="text" v-model='number1'> 不能用props属性值 会报错-->
         <input type="text" v-bind:value='dnumber1' @input='number1input'> 
      </h2>
    </div>
  </template>
  
  <script>
  //子组件 
  const cpn = {
    template:'#cpn',
    
    props:{
      number1:Number
    },
    
    data(){
      return{
        dnumber1 : this.number1
      }
    },
   
    methods:{
         number1input(event){
           //this.number1=event.target.value //不能直接修改
           this.dnumber1=event.target.value
           this.$emit('num1change',this.dnumber1)
         }
     },
  }
  
  //父组件
  const app = new Vue({
    el:"#app",
    data:{
      num1 :1,
      num2 :0
    },
   
    components:{
      cpn
    },
     methods:{
      num1change(value){
        //this.num1= value*1
        this.num1= parseInt(value)
      }
    }
  })
  </script>
</html>
View Code

 最终效果

原文地址:https://www.cnblogs.com/polax/p/12927518.html