亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

vue中使用v-model完成組件間的通信

 更新時(shí)間:2019年08月22日 10:09:41   作者:麥籬落  
vue中有一個(gè)很神奇的東西叫v-model,它可以完成我們的需求。,本文重點(diǎn)給大家介紹vue中使用v-model完成組件間的通信,需要的朋友可以參考下

以上的兩種方法,都是實(shí)現(xiàn)的單向數(shù)組傳遞,那如何實(shí)現(xiàn)兩個(gè)組件之間的雙向傳遞呢?

即,在父組件中修改了值,子組件會(huì)立即更新。

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

vue中有一個(gè)很神奇的東西叫v-model,它可以完成我們的需求。

使用v-model過程中,父組件我們還是需要將子組件正常引入,只是傳值方式改成了v-model

父組件

<template>
 <div>
 {{fatherText}}
 <Child v-model="fatherText"></Child>//調(diào)用子組件,并將 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的值,并添加一個(gè)修改值 的方法
 </div>
</template>
<script>
export default {
 name: "child",
 model: {//添加了model方法,用于接收v-model傳遞的參數(shù)
 prop: "fatherText", //父組件中變量的傳遞
 event: "changeChild" //事件傳遞
 },
 props: {
 fatherText: {//正常使用props接收fatherText的值
 type: String
 }
 },
 data() {
 return {
 
 };
 },
 methods: {
 change(){
  this.fatherText = 'son change the text'
 }
 }
};
</script>

在這里,報(bào)了一個(gè)錯(cuò)誤,這是因?yàn)閿?shù)據(jù)流是單向的,但是我們?cè)谶@里,子組件不應(yīng)該直接修改props里的值。

 

這里不能直接修改,所以我們需要迂回著修改,在子組件中定義一個(gè)自己的變量,再將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";//修改自己的變量
 }
 }
};

兩個(gè)組件間更新

完成了上述代碼,你會(huì)發(fā)現(xiàn)兩個(gè)組件都改變的內(nèi)容,但是只更新了自身組件的內(nèi)容,如何使兩個(gè)組件進(jìn)行同步更新呢?

這里需要使用我的Wath方法,來進(jìn)行監(jiān)聽傳遞組件的變量

<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) {//使用父組件中變量名為函數(shù)名,監(jiān)聽fatherText的變化,如果變化,則改變子組件中的值
 this.childText = newtext;
 },
 childText(newtext) {//監(jiān)聽子組件中childText變化,如果變化,則通知父組件,進(jìn)行更新
 this.$emit("changeChild", newtext);
 }
 }
};

總結(jié)

以上所述是小編給大家介紹的vue中使用v-model完成組件間的通信希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!

相關(guān)文章

最新評(píng)論