1、正常的父子组件传值
2、使用sync 实现父子组件传值
3、使用v-model实现父子组件传值
<div id="app">
</div>
//正常 emit传值
Vue.component('my-component', {
template: `<div>
{{msg}}:<my-counter :cont="msg" @add="change" />
</div>`,
data:function(){
return {
msg:1212
}
},
methods: {
change(val){
this.msg = val;
}
}
});
Vue.component("my-counter", {
template: `<div>
<button @click="add">++</button>
</div>`,
props: ['cont'],
methods: {
add(){
this.$emit('add',this.cont+1)
}
}
});
new Vue({
el: '#app'
})
// 通过.aync
Vue.component('my-component', {
template: `<div>
{{msg}}:<my-counter :cont.sync="msg" />
</div>`,
data:function(){
return {
msg:1212
}
},
methods: {
change(val){
this.msg = val;
}
}
});
Vue.component("my-counter", {
template: `<div>
<button @click="add">{{cont}}++</button>
</div>`,
props: ['cont'],
methods: {
add(){
this.$emit('update:cont',this.cont+1)
}
}
});
new Vue({
el: '#app',
template:"<my-component />"
})
//通过v-model 第一种
Vue.component('my-component', {
template: `<div>
{{msg}}:<my-counter v-model="msg" />
</div>`,
data:function(){
return {
msg:1212
}
},
methods: {
change(val){
this.msg = val;
}
}
});
Vue.component("my-counter", {
template: `<div>
<button @click="add">{{msg}}++</button>
</div>`,
model:{
prop:'msg',
event:'change'
},
props: ['msg'],
methods: {
add(){
this.$emit('change',this.msg+1)
}
}
});
new Vue({
el: '#app',
template:"<my-component />"
})
//通过v-model 第二种 写在最后推荐
Vue.component('my-component', {
template: `<div>
{{msg}}:<my-counter v-model="msg" />
</div>`,
data:function(){
return {
msg:1212
}
},
methods: {
change(val){
this.msg = val;
}
}
});
Vue.component("my-counter", {
template: `<div>
<button @click="add">{{value}}++</button>
</div>`,
props: ['value'],
methods: {
add(){
this.$emit('input',this.value+1)
}
}
});
new Vue({
el: '#app',
template:"<my-component />"
})
网友评论