Vue父子組件雙向綁定傳值的實(shí)現(xiàn)方法-創(chuàng)新互聯(lián)

父子組件之間的雙向綁定非常簡(jiǎn)單,但是很多人因?yàn)槭菑腣ue 2+開始使用的,可能不知道如何雙向綁定,當(dāng)然最簡(jiǎn)單的雙向綁定(單文件中)就是表單元素的 v-model 了,例如 <input type="text" /> 它會(huì)響應(yīng)表單元素的 value 屬性,當(dāng)輸入框文本改變時(shí),會(huì)將 value 值傳給 v-model 所綁定的變量,如果同時(shí)設(shè)置 v-model 和 value , value 屬性無(wú)效。

創(chuàng)新互聯(lián)2013年至今,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目網(wǎng)站制作、成都做網(wǎng)站網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元東昌府做網(wǎng)站,已為上家服務(wù),為東昌府各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:18980820575

父子組件的自定義雙向 v-model

當(dāng)若干dom封裝成組件時(shí),在父組件中使用子組件時(shí),卻無(wú)法在子組件標(biāo)簽上使用 v-model ,因?yàn)樽咏M件標(biāo)簽不是表單元素,這個(gè)時(shí)候,我們需要自定義我們想要的 v-model 規(guī)則。

<!-- children.vue -->
<template>
 <h2>{{ msg }}</h2>
</template>
<script>

export default{
 model:{
  prop:'msg',//這個(gè)字段,是指父組件設(shè)置 v-model 時(shí),將變量值傳給子組件的 msg
  event:'parent-event'//這個(gè)字段,是指父組件監(jiān)聽 parent-event 事件
 },
 props:{
  msg:String //此處必須定義和model的prop相同的props,因?yàn)関-model會(huì)傳值給子組件
 },
 mounted(){
 //這里模擬異步將msg傳到父組件v-model,實(shí)現(xiàn)雙向控制
  setTimeout(_=>{
   let some = '3秒后出現(xiàn)的某個(gè)值';//子組件自己的某個(gè)值
   this.$emit('praent-event',some);
   //將這個(gè)值通過(guò) emit 觸發(fā)parent-event,將some傳遞給父組件的v-model綁定的變量
  },3000);
 }
}
</script>

<!-- parent.vue -->
<template>
 <children v-model="parentMsg"></children>
</template>
<script>
import children from 'path/to/children.vue';
export default{
 components:{
  children
 },
 data(){
  return{
   parentMsg:'test'
  }
 },
 watch:{
  parentMsg(newV,oldV){
   console.log(newV,oldV);
   //三秒后控制臺(tái)會(huì)輸出
   //'3秒后出現(xiàn)的某個(gè)值','test'
  }
 }
}
</script>

網(wǎng)站欄目:Vue父子組件雙向綁定傳值的實(shí)現(xiàn)方法-創(chuàng)新互聯(lián)
轉(zhuǎn)載來(lái)于:http://bm7419.com/article38/hsipp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計(jì)公司、App設(shè)計(jì)、自適應(yīng)網(wǎng)站商城網(wǎng)站、全網(wǎng)營(yíng)銷推廣服務(wù)器托管

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

搜索引擎優(yōu)化