Vue父子組件雙向綁定傳值的實現方法


從某方面講,父組件傳值給子組件進行接收,之后在子組件中更改是不允許的。你會發現vue也會直接報錯,而在封裝一些組件的時候,又希望做到數據的雙向綁定,可以更好的控制與使用,在網上找到了兩種方法,一種的話是使用 v-model 還有一種是 .sync
這里我推薦使用.sync

原因:v-mode只能進行單個雙向綁定值而使用.sync可支持多個雙向綁定值,當然,具體使用哪個可以參照自己的使用場景來區分

這里我就來寫個通過.sync 實現父子數據雙向綁定的例子

 

代碼如下:

這是父組件

vi設計http://www.maiqicn.com 辦公資源網站大全https://www.wode007.com

<template> <div class="home"> <!-- 此處只需在平時常用的單向傳值上加上.sync修飾符 --> <HelloWorld :msg.sync="parentMsg" :msg2.sync="parentMsg2" /> </div> </template> <script> import HelloWorld from '@/components/HelloWorld.vue' export default { name: 'home', data(){ return{ parentMsg:'test', parentMsg2:'test2' } }, watch:{ // 監聽數據的變化輸出 newV 改變的值,oldV 改變之前的值 parentMsg(newV,oldV){ console.log(newV,oldV); }, parentMsg2(newV,oldV){ console.log(newV,oldV); } }, components: { HelloWorld } } </script> 

子組件

<template> <div> <h1>{{ msg }}</h1> <h1>{{ msg2 }}</h1> <button @click="fn()">點擊</button> </div> </template> <script> export default{ props:{ msg:String, msg2:String }, methods:{ fn(){ let some = '張三'; let some2 = '李四'; // 將這個值通過 emit // update為固定字段,通過冒號連接雙向綁定的msg,將some傳遞給父組件的v-model綁定的變量 this.$emit('update:msg',some); this.$emit('update:msg2',some2); } } } </script> 

此處需要注意,雖然加上 .sync 即可雙向綁定,但是還是要依靠子組件 $emit 去觸發 update:prop名 實現修改父組件的變量值實現雙向數據流,如果直接對prop的屬性直接賦值,依然會出現報錯。

事實上, .sync 修飾符是一個簡寫,它做了一件事情

<template> <HelloWorld :msg.sync="parentMsg" :msg2.sync="parentMsg2" /> <!-- 等價於 --> <HelloWorld :msg="parentMsg" @updata:msg="parentMsg = $event"></HelloWorld> <!-- 這里的$event就是子組件$emit傳遞的參數 --> </template>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM