vue 利用v-model實現父子組件數據雙向綁定 (input)


一、實現動態傳值

<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>

二、v-model實現原理

<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>


免責聲明!

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



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