Vue 父子组件双向绑定传值
生活随笔
收集整理的這篇文章主要介紹了
Vue 父子组件双向绑定传值
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最簡單的雙向綁定(單文件中)就是表單元素的v-model了,如果同時設置v-model和value,value屬性無效。
自定義v-model:(不推薦)
child: <template><h1>{{ msg }}</h1> </template>export default{model:{prop:'msg', // 指父組件設置 v-model 時,將變量值傳給子組件的 msgevent:'parent-event' // 指父組件監聽 parent-event 事件},props:{msg:String // 此處必須定義和model的prop相同的props,因為v-model會傳值給子組件},mounted(){// 這里模擬異步將msg傳到父組件v-model,實現雙向控制setTimeout(_=>{let some = '3秒后出現的某個值'; // 子組件自己的某個值this.$emit('parent-event', some); //通過 emit 觸發parent-event,將some傳遞給父組件的v-model綁定的變量}, 3000);} } </script> parent: <template><children v-model="parentMsg"></children> </template> <script> import children from './children.vue'; export default{components:{children},data(){return{parentMsg:'test'}},watch:{parentMsg(newV, oldV){console.log(newV,oldV);//三秒后控制臺會輸出//'3秒后出現的某個值','test'}} } </script>自定義多個雙向值(推薦):.sync修飾符
child: <template><h1>{{ msg }}</h1> </template> <script>export default{props:{msg:String},mounted(){setTimeout(_=>{this.$emit('update:msg',some);},3000);} } </script> parent: <template><children :msg.sync="parentMsg"></children><!-- 此處只需在平時常用的單向傳值上加上.sync修飾符 --> </template> <script> import children from './children.vue'; export default{components:{children},data(){return{parentMsg:'test'}},watch:{parentMsg(newV,oldV){console.log(newV,oldV);}} } </script>鏈接:https://juejin.im/post/5b5c2d986fb9a04f897840ac
來源:掘金
總結
以上是生活随笔為你收集整理的Vue 父子组件双向绑定传值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Unity3D】2D动画
- 下一篇: Javascript屏蔽鼠标的右键的两种