【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属性向子组件传入的值被修改以后报错的问题