溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

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

發布時間:2021-05-08 15:22:33 來源:億速云 閱讀:260 作者:小新 欄目:web開發

這篇文章主要介紹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完成組件間的通信”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女