vue 自定義組件 v-model


平時在開發項目寫組件時,父子組件間相互傳值,父組件傳遞過去的值通過props,遵循單向數據流規則,子組件不可修改父組件傳遞過來的值,如需修改需要使用this.$emit('自定義屬性', this.XXX),類似這種情況可以使用 v-model 更為合適

平時我們使用 v-model 一般用在 input 標簽上

1  <input v-model= 'content' ></input>
2  
3  export default{
4        data(){
5             return {
6                  content: ' '
7             }
8        }
9  }

等價於

 1 <input v-bind:value='content' v-on:input='content = $event.target.value' ></input>             

用在組件上類似於

1 Vue.component( 'base-input' , {
2        props: ['value'],
3        template:` <input v-bind:value = 'value'  v-on:input = "$emit( 'input', $emit.target.value )" ></input> `
4 })

一個組件上的 v-model 默認會利用名為 value 的 prop 和名為 input 的事件

所以當我們把 v-model 用在自定義組件上時

 1 父組件:
 2 <Child  v-model = 'flag' ></Child>
 3 export default {
 4      data(){
 5         return {
 6             flag: true
 7         }
 8     }
 9 }
10 
11 子組件:
12 <button @click = "$emit( 'input',!value )" ></button>
13 export default {
14      props: {
15          value: Boolean
16      }
17 }

父組件使用 v-model 綁定在data中定義的屬性 flag 傳遞給子組件(Child),子組件通過 props 接收,名為 value ,通過按鈕觸發對父組件中 flag 進行修改 ( $emit( 'input',!value ) )

 

通過在model屬性中自定義事件:

如果遇到單選框、復選框等類型的輸入控件可能會將 value attribute 用於不同的目的,model 選項可以用來避免這樣的沖突:

 1 父組件:
 2  <Child  v-model = ‘flag’></Child>
 3 export default {
 4         data() {
 5               return { 
 6                    flag:true
 7               }
 8         }
 9 }
10 
11 子組件:
12 <button @click = " $emit('aliasFlag', !flag)"></button>
13 export default {
14          props:{
15                 flag: Boolean
16           },
17          model:{
18                 prop: 'flag',
19                 event: 'aliasFlag'
20          }
21 }

通過使用 model 里的 event 方法自定義屬性名,prop代表和props里的變量相對應

 


免責聲明!

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



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