当前位置: 移动技术网 > IT编程>开发语言>JavaScript > vue中使用v-model完成组件间的通信

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

2019年09月06日  | 移动技术网IT编程  | 我要评论

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

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

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

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完成组件间的通信希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网