關於vue的model屬性


我們常用的指令中v-model

他實際上是語法糖

<template>
  <input v-model="value"/>
</template>

<script>
export default {
  data() {
    return {
        value:''
    };
  }
};
</script>

 

 

等於以下寫法

 

<template> 
  <input :value="value" @input="(event)=>{value=event.value}"/>
</template>

<script>
export default {
  data() {
    return {
        value:''
    };
  }
};
</script>

 

 

 這種寫法在於,input的value屬性和input方法是固有的內容,所以v-model可以約定成俗的直接調用這兩者,

 但我們自定義的組件可沒有這種固有屬性與對應的固有方法,那么model就用來設置這種關系的屬性

//myComponent內部
<template>
    <p>{{isMessage}}</p>
</template>

<script>
export default {
  model:{
      prop:'message',// v-model接收的值=props的message屬性接收的值
      event:'change'//v-model發生變化時觸發的方法
  },
  props:{
    message:{
        type:string,
        default:''
    }
  },
  data() {
    return {
        isMessage:''"
    };
  },
  methods:{
    change(value){
        console.log(value)
    }
  }
};
</script>

 

 

外部使用

<template>
  <myComponents v-model="aaa"></myComponents >
</template>

<script>
import myComponent from ‘xxx/xxx/myComponent.vue’

export default {
  cpmponents:{
    myComponent
  },
  data() {
    return {
        aaa:''"
    };
  }
};
</script>

 


免責聲明!

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



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