使用 v-model 實現 雙向綁定.(子組件和父組件.)


vue 自定義組件 v-model雙向綁定、 父子組件同步通信

 

父子組件通信,都是單項的,很多時候需要雙向通信。方法如下:

  1、父組件使用:msg.sync="aa"  子組件使用$emit('update:msg', 'msg改變后的值xxx') 

  2、父組件傳值直接傳對象,子組件收到對象后可隨意改變對象的屬性,但不能改變對象本身。

  3、父組件使用: v-model 

  第一種曾經被廢除過,由於維護成本的原因被刪掉,但經過證實,確實有存在的意義,又被加上。

  第一種:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
父組件:
     <template>
   <div>
     <aa  class = "abc"  :snycTest.sync= "test"  ></aa>
       {{ '外面的值:'  + test}}
     <button @click= "fn" >
       外面改變里面
     </button>
     
   </div>
</template>
 
<script>
import  aa from  './test.vue'
   export  default  {
     data () {
       return  {
         test:  ''
       }
     },
     methods: {
       fn () {
         this .test += 1
       }
     },
     components:{
       aa
     }
   }
</script>

  

復制代碼
子組件:
 <template>
  <div>
    <ul>
      <li>{{'里面的值:'+ snycTest}}</li>
      <button @click="fn2">里面改變外面</button>
    </ul>
  </div>
</template>

<script>
  export default {
    props: {
      snycTest: ''
    },
    methods: {
      fn2 () {
        this.$emit('update:snycTest', this.snycTest+1) //這兒是關鍵 update:snycTest 自定義事件會告訴父組件將父組件的 test值改為this.snycTest+1,並傳回給子組件。
} } } </script>
復制代碼

v-model寫法一:

復制代碼
父組件:
 <template>
  <div>
    <aa class="abc" v-model="test" ></aa>  // 組件中使用v-model
      {{'外面的值:' + test}} // 這兒試驗test與內部msg值為雙向綁定關系
    <button @click="fn">
      外面改變里面
    </button>
    
  </div>
</template>

<script>
import aa from './test.vue'
  export default {
    data () {
      return {
        test: ''
      }
    },
    methods: {
      fn () {
        this.test += 1 
      }
    },
    components:{
      aa
    }
  }
</script>
復制代碼
復制代碼
子組件寫法一:
<template>
  <div>
    <ul>
      <li>{{'里面的值:'+ msg}}</li>
      <button @click="fn2">里面改變外面</button>
    </ul>
  </div>
</template>

<script>
  export default {
    model: {    // 使用model, 這兒2個屬性,prop屬性說,我要將msg作為該組件被使用時(此處為aa組件被父組件調用)v-model能取到的值,event說,我emit ‘cc’ 的時候,參數的值就是父組件v-model收到的值。
      prop: 'msg',
      event: 'cc'
    },
    props: {
      msg: ''
    },
    methods: {
      fn2 () {
        this.$emit('cc', this.msg+2)
      }
    }
  }
</script> 
 
           
復制代碼

v-model寫法二

  父組件 <aa class="abc" v-model='test' ></aa> 。
復制代碼
子組件
<template>
 <div>
    <ul>
      <li>{{'里面的值:'+ value}}</li> // 組件使用時有v-model屬性,value初始傳的‘what’ 不會被渲染,而是v-model綁定的test值被渲染,這兒value會被重新賦值為v-model綁定的test的值。
      <button @click="fn2">里面改變外面</button>
    </ul>
  </div>
</template>

<script>
  export default {
    props: {
      value: { // 必須要使用value
     default: '',
    }, }, methods: { fn2 () { this.$emit('input', this.value+2) // 這兒必須用input 發送數據,發送的數據會被父級v-model=“test”接受到,再被value=test傳回來。 } } }
復制代碼

一般雙向綁定用v-model寫法一。

    

 
 
標簽:  vue2自定義組件v-model


免責聲明!

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



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