一、实现动态传值
<body>
<script src="https://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
<div id="box">
<new-input v-model="name"></new-input>
{{name}}
</div>
<script>
Vue.component('new-input',{
props: ['value'],
template:'<label><input type="text" v-model="newValue" /> 你的名字:</label>',
computed:{
newValue: {
get:function() {
return this.value;
},
set:function(value) {
this.$emit('input', value);
}
}
},
});
new Vue({
el:'#box',
data: {
name:'nick'
}
});
</script>
</body>
二、v-model实现原理
<body>
<script src="https://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
<div id="box">
<input :value="name" @input="changeValue($event.target.value)"/>
{{ name }}
</div>
<script>
new Vue({
el:'#box',
data: {
name:'nick'
},
methods:{
changeValue:function(value){
this.name = value;
}
}
});
</script>
</body>