組件通信之props

一、props不為對(duì)象
 //子組件中不能修改props傳入的值 會(huì)引發(fā)vue報(bào)錯(cuò) 一般在mounted之后將其值賦予新的變量
<template>
  <div>
    <p>I Am The Data Of Parent: {{ parentData }}</p>
    <child :childData="parentData "></child>
  </div>
</template>

<script>
  import Vue from 'vue';

  const child = Vue.extend({
    template: '<p>I Am The Data Of Child: {{ childData}}</p>',
    props: {
      childData: { type: String, required: true }
    },
    methods: {
      changeChildData() {
        setTimeout(() => {
           this.childData = 'newnewnew';
        }, 1000);
      }
    },
    mounted() {
      this.changeChildData();
    }
  });

export default {
  data() {
    return { parentData: 'oldoldold' };
  },
  methods: {
    changeParentData() {
      setTimeout(() => {
        this.parentData = 'pnewpnewpnew';
      }, 666);
    }
  },
  mounted() {
    this.changeParentData();
  },
  componts: { child }
};
</script>

當(dāng)父組件修改props的值時(shí)子組件中值跟隨改變;當(dāng)子組件中值改變時(shí) 報(bào)錯(cuò) 且父組件值無變化;

二、props為對(duì)象
  //修改props傳入對(duì)象屬性即可 父組建屬性跟隨改變( 同樣不能直接修改整個(gè)對(duì)象 )
<template>
  <div>
    <p>I Am The Data Of Parent: {{ parentData.data }}</p>
    <child :childData="parentData "></child>
  </div>
</template>

<script>
  import Vue from 'vue';

  const child = Vue.extend({
    template: '<p>I Am The Data Of Child: {{ childData.data }}</p>',
    props: {
      childData: { type: Object, required: true }
    },
    methods: {
      changeChildData() {
        setTimeout(() => {
           // this.childData = { **** }; error
           this.childData.data = 'newnewnew';
        }, 1000);
      }
    },
    mounted() {
      this.changeChildData();
    }
  });

export default {
  data() {
    return { parentData: { data: 'oldoldold' } };
  },
  methods: {
    changeParentData() {
      setTimeout(() => {
        // this.parentData = { **** };  run
        this.parentData.data = 'pnewpnewpnew';
      }, 666);
    }
  },
  mounted() {
    this.changeParentData();
  },
  componts: { child }
};
</script>

父子組件修改值時(shí)相互影響

建議props總是用對(duì)象;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容