天天看點

【Vue】11.解決父元件通過props屬性向子元件傳入的值被修改以後報錯的問題

我在做vue項目的時候遇到了這樣的一個問題,在這裡做一下總結,就是在送出表單的時候會有一個彈框提醒,這個Dialog我把它封裝成了一個子元件,這樣在父元件的data屬性裡面就會定義一個Dialog顯示還是隐藏的變量,這個變量預設是false,點選按鈕的時候這個變量要變成true顯示Dialog,完了以後要關閉Dialog按鈕,這個變量就要從父元件傳入子元件,在子元件裡面改變以後再傳回父元件,這裡我不是要說vue裡面dialog如何實作,是以不貼dialog實作的代碼,重點是我在改變這個變量的時候遇到了一個問題,是以寫了一個小demo示範一下。

【Vue】11.解決父元件通過props屬性向子元件傳入的值被修改以後報錯的問題

 我們都知道在vue中,父元件傳入子元件的變量是存放在props屬性中的,我們在調用變量的時候是跟data裡面的變量一樣的,都是通過this.變量來調用,這個問題就是說從父元件傳入子元件的變量是不能this.變量直接改變的,要在data或者computed屬性裡面重新定義一個變量,改變data或者computed屬性裡面的變量就不會報錯了。

父元件Parent.vue

<template>
    <div>
      <child :fatherMethod="fatherMethod" :message="name" @childByValue="childByValue"></child>
    </div>
</template>

<script>
  import Child from '../../components/Child.vue';

    export default {
      data() {
        return {
          name: 'Parent',
        };
      },
      methods: {
        fatherMethod() {
          console.log('testing');
        },
        // 子元件傳回父元件的值
        childByValue(childValue) {
          console.log(childValue);
        },
      },
      components: {
        child: Child,
      },
    };
</script>

<style scoped>

</style>
           

子元件Child.vue

<template>
  <div>
    <button @click="childMethod">點選</button>
  </div>
</template>

<script>
  export default {
    props: ['fatherMethod', 'message'],
    data() {
      return {
        name: 'Child',
        changeMessage: this.message,
      };
    },
    created() {
      this.fatherMethod();
      // this.message = `hello ${this.message}`; // 報錯
      this.changeMessage = `hello ${this.message}`; // 不報錯
      console.log(this.message);
    },
    computed: {
      changeMessage1() {
        return `hello1 ${this.message}`;
      },
    },
    methods: {
      childMethod() {
        this.fatherMethod();
        this.$emit('childByValue', this.changeMessage);
        this.$emit('childByValue', this.changeMessage1);
      },
    },
  };
</script>

<style scoped>

</style>
           
【Vue】11.解決父元件通過props屬性向子元件傳入的值被修改以後報錯的問題

繼續閱讀