vue中子組件修改父子變量報錯問題

通過子組件中變量變化 修改父頁面中變量報如下錯:

  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: "XXX"

解決方案:

1、父頁面中 

<template>  
    <train-city @ChangeName="ChangeName" :isData=" isOpen"></train-city>  
<template>  
<script>  
  import TrainCity from "./train-city";  
  export default {  
    name:'index',  
    components: {TrainCity},  
    data () {  
      return {  
        isOpen:false 
      }  
    },  
    methods:{  
      ChangeName(data){   //在子組件觸發的事件  
        this.isOpen= data.isOpen;//改變了父組件的值  
      }  
    }  
  }  
</script>

組件中

<template>  
  <div class="stuts">  
    <br/><button @click='select(`true`)'>點擊事件</button>  
  </div>  
</template>  
<script>  
  export default {  
    name:'trainCity',  
    props:['isData'], // 用來接收父組件傳的值  
    methods:{  
      changeVal(val) {  
        let data = {  
          isOpen: val  
        };  
        this.$emit('ChangeName',data);觸發ChangeName事件  
      }  
    }  
  }  
</script>

 

2、如果條件允許可以直接在組件中定義變量

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章