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

这篇文章主要介绍vue中如何使用v-model完成组件间的通信,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

Vue的优点

Vue具体轻量级框架、简单易学、双向数据绑定、组件化、数据和结构的分离、虚拟DOM、运行速度快等优势,Vue中页面使用的是局部刷新,不用每次跳转页面都要请求所有数据和dom,可以大大提升访问速度和用户体验。

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

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里的值。

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

这里不能直接修改,所以我们需要迂回着修改,在子组件中定义一个自己的变量,再将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完成组件间的通信”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注行业资讯频道!