Vue2.0的v-model指令
Vue2.0的v-model指令
v-model="属性" 写在标签中上,相当于在一个标签上,同时写了 :value='属性值' @iinput='handler' ,而handler对应的函数如果没有声明,就是给该属性值赋值的setter函数
代码一:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../js/vue.min.js"></script>
</head>
<body>
<div id="app">
<p>总数:{{total}}</p>
<!-- 在自定义组件上使用v-model指令 -->
<my-component v-model="total"></my-component>
</div>
<div id="app1">
<p>总数:{{total}}</p>
<!--第一种写法实际就是这种写法 -->
<my-component @input="handleGetTotal"></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);
}
}
});
Vue.component('my-component1',{
template:'<button @click="handleClick">+1</button>',
data:function(){
return {
counter:0
}
},
methods: {
handleClick:function(){
this.counter++;
this.$emit('input',this.counter);
}
}
});
let app=new Vue({
el:"#app",
data:{
total:0
}
});
let app1=new Vue({
el:"#app1",
data:{
total:0
},
methods:{
handleGetTotal:function(total){
this.total=total;
}
}
});
</script>
</body>
</html>
代码二:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../js/vue.min.js"></script>
</head>
<body>
<div id="app">
<p>总数:{{total}}</p>
<!-- 在自定义组件上使用v-model指令 -->
<my-component v-model="total"></my-component>
</div>
<div id="app1">
<p>总数:{{total}}</p>
<!--第一种写法实际就是这种写法 -->
<my-component @input="handleGetTotal"></my-component>
</div>
<script>
Vue.component('my-component2',{
props:['value'],//?
// 接收一个value属性,在有新的value时触发input事件
template:'<input :value="value" @input="updateValue">',
methods: {
updateValue:function(event){
this.$emit('input',event.target.value);
}
}
});
Vue.component('my-component3',{
props:['value'],//?
// 接收一个value属性,在有新的value时触发input事件
template:'<input :value="value" @input="updateValue">',
methods: {
updateValue:function(event){
this.$emit('input',event.target.value);
}
}
});
let app2=new Vue({
el:"#app2",
data:{
total:0
},
methods:{
handleReduce:function(total){
this.total--;
}
}
});
let app3=new Vue({
el:"#app3",
data:{
total:0
},
methods:{
handleGetTotal:function(total){
this.total=total;
},
handleReduce:function(total){
this.total--;
}
}
});
</script>
</body>
</html>

浙公网安备 33010602011771号