v-model通常用於input的雙向數據綁定 <input v-model="parentMsg">,也可以實現子組件到父組件數據的雙向數據綁定:
首先說說v-model的用法:
父組件:
<div>
<input type="text" v-model='msg'>
<child v-model='msg'></child>
</div>
子組件:
Vue.component('child', {
props: ['value'],
template: '<input type="text" @input="handleInput" :value=value />',
methods: {
handleInput(e){
console.log(e);
this.$emit('input', e.target.value);
}
}
})
new Vue({
el:'#example',
data:{
msg:'好天氣',
parentMsg:''
}
})
無論改變父組件還是子組件的輸入框,value和msg的值都會改變,兩個輸入框的值也就同時改變了。
:model和v-model的區別
:model是v-bind:model的縮寫,<child :model="msg"></child>這種只是將父組件的數據傳遞到了子組件,並沒有實現子組件和父組件數據的雙向綁定。當然引用類型除外,子組件改變引用類型的數據的話,父組件也會改變的。
