v-model
在自定義的組將直接綁定父組件中的數(shù)據(jù)變量,在自定義組件中將需要綁定的值發(fā)送給v-model綁定的變量。
<div id='app'>
<p>{{total}}</p>
<my-component v-model="total"></my-component>
</div>
<script>
Vue.component('my-component', {
template: '<button @click="handleClick"> +1 </button>',
data: function () {
return {
counter: 0
}
},
methods: {
handleClick: function () {
this.counter++;
this.$emit('input', this.counter);
}
}
});
var app = new Vue({
el: '#app',
data: {
total: 0
}
})
</script>
原理
默認實現(xiàn)了@input='handle'
的事件,以v-model
代替
<div id='app'>
<p>{{total}}</p>
<my-component @input="handleGetTotal"></my-component>
</div>
<script>
// ...組件代碼
var app = new Vue({
el: '#app',
data: {
total: 0
},
methods: {
handleGetTotal: function (total) {
this.total = total
}
}
})
</script>
數(shù)據(jù)雙向綁定
在自定義組件中接收value
屬性,當有新的值時拐邪,傳遞到綁定的v-model
<div id='app'>
<p>{{total}}</p>
<my-component v-model="total"></my-component>
<button @click="handelReduce"> -1 </button>
</div>
<script>
Vue.component('my-component', {
props: ['value'],
template: '<input :value="value" @input="updateValue" />',
methods: {
updateValue: function (event) {
this.$emit('input', event.target.value);
}
}
});
var app = new Vue({
el: '#app',
data: {
total: 0
},
methods: {
handelReduce: function () {
this.total--;
}
}
})
</script>
以modal
為例,一般在data中創(chuàng)建value
的副本隘截,在watch
中監(jiān)聽扎阶,當改變后同步到v-modal
<template>
<div class="modal" :value="value" v-show="visible">
<div class="close" @click="cancel">X</div>
</div>
</template>
<script>
export default {
props: {
value: {
type: Boolean,
default:false
}
},
data () {
return {
visible:false
}
},
watch: {
value(val) {
this.visible = val;
},
visible(val) {
this.$emit('input', val);
}
},
methods: {
cancel(){
this.visible = false;
}
},
mounted() {
if (this.value) {
this.visible = true;
}
}
}
</script>
<modal v-model="isShow"></modal>
export default {
name: 'app',
data () {
return {
isShow:false
}
}
}
</script>
另一種寫法
我覺得相當于重命名了value
和input
<template>
<div class="modal" :value="renameValue" v-show="visible">
<div class="close" @click="cancel">X</div>
</div>
</template>
<script>
export default {
model: {
prop: 'renameValue',
event: 'renameInput'
},
props: {
renameValue: {
type: Boolean,
default: false
}
},
data () {
return {
visible:false
}
},
watch: {
renameValue(val) {
this.visible = val;
},
visible(val) {
this.$emit('renameInput', val);
}
},
methods: {
cancel(){
this.visible = false;
}
},
mounted() {
if (this.renameValue) {
this.visible = true;
}
}
}
</script>