vue中使用v-model完成组件间的通信

摘要:如何实现两个组件之间的双向传递呢?即,在父组件中修改了值,子组件会立即更新。在子组件中修改了值,父组件中立即更新。vue中有一个很神奇的东西叫v-model,它可以完成我们的需求。

父子传递“双向绑定”

如何实现两个组件之间的双向传递呢?即,在父组件中修改了值,子组件会立即更新。在子组件中修改了值,父组件中立即更新。

vue中有一个很神奇的东西叫v-model,它可以完成我们的需求。

使用v-model过程中,父组件我们还是需要将子组件正常引入,只是传值方式改成了v-model

父组件

<template>
  <div>
    {{fatherText}}
    <Child v-model="fatherText"></Child>//调用子组件,并将 fatherText传递给子组件
    <button @click="changeChild">changeChildButton</button>
  </div>
</template>

<script>
import Child from "./Child.vue";
export default {
  name: "father",
  data() {
    return {
      fatherText: "i'm fathertext"
    };
  },
  components: {
    Child
  },
  methods: {
    changeChild() {
      this.fatherText = "father change the text";
    }
  }
};
</script>

子组件

<template>
  <div>
   <p class="child" @click="change">{{fatherText}}</p>//正常使用fatherText的值,并添加一个修改值 的方法
  </div>
</template>
<script>
export default {
  name: "child",
  model: {//添加了model方法,用于接收v-model传递的参数
    prop: "fatherText", //父组件中变量的传递
    event: "changeChild" //事件传递
  },
  props: {
    fatherText: {//正常使用props接收fatherText的值
      type: String
    }
  },
  data() {
    return {
     
    };
  },
  methods: {
      change(){
          this.fatherText = 'son change the text'
      }
  }
};
</script>

在这里,报了一个错误,这是因为数据流是单向的,但是我们在这里,子组件不应该直接修改props里的值。
这里不能直接修改,所以我们需要迂回着修改,在子组件中定义一个自己的变量,再将props的值赋值到自己的变量,修改自己的变量是可以的。


子组件 - 修改props中的值

<template>
  <div>
    <p class="child" @click="change">{{childText}}</p>
  </div>
</template>
<script>
export default {
  name: "child",
    model: {
    prop: "fatherText", //父组件中变量的传递
    event: "changeChild" //事件传递
  },
  props: {
    fatherText: {
      type: String
    }
  },
  data() {
    return {
      childText: this.fatherText //定义自己的变量childText
    };
  },
  methods: {
    change() {
      this.childText = "son change the test";//修改自己的变量
    }
  }
};

两个组件间更新
完成了上述代码,你会发现两个组件都改变的内容,但是只更新了自身组件的内容,如何使两个组件进行同步更新呢?

这里需要使用我的Wath方法,来进行监听传递组件的变量

<template>
  <div>
    <p class="child" @click="changeChild">{{childText}}</p>
  </div>
</template>
<script>
export default {
  name: "child",
  model: {
    prop: "fatherText", //父组件中变量的传递
    event: "changeChild" //事件传递
  },
  props: {
    fatherText: {
      type: String
    }
  },
  data() {
    return {
      childText: this.fatherText
    };
  },
  methods: {
    changeChild() {
      this.childText = "son change the test";
    }
  },
  watch: {
    fatherText(newtext) {//使用父组件中变量名为函数名,监听fatherText的变化,如果变化,则改变子组件中的值
      this.childText = newtext;
    },
    childText(newtext) {//监听子组件中childText变化,如果变化,则通知父组件,进行更新
      this.$emit("changeChild", newtext);
    }
  }
};

本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_4848