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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

麦篱落   2020-05-17 我要评论

以上的两种方法,都是实现的单向数组传递,那如何实现两个组件之间的双向传递呢?

即,在父组件中修改了值,子组件会立即更新。

在子组件中修改了值,父组件中立即更新。

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);
 }
 }
};

总结

以上所述是小编给大家介绍的vue中使用v-model完成组件间的通信希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们