基于以下情况
//父组件
data:{
//对象形式
}
//子组件
data:function(){
return {
//函数形式
}
}
例子如下
<div id="app">
//父组件
<p>{{total}}</p>
<mime @increment1="incrementTotal" ref="child" :num-a="total" num-s="total"></mime>
<button type="button" @click="clickref">调用子组件</button>
</div>
//子组件
<template id="myInput">
<button @click="add">{{counter}}</button>
</template>
<script>
new Vue({
el:'#app',
data :{
total: 0
},
methods:{
incrementTotal : function(){
},
clickref:function(){
}
},
components:{
'mime' :{
template:'#myInput',
data : function(){
return{
counter : 0
}
},
props:['numA','numS'],
methods:{
add : function(){
}
}
}
}
});
</script>
子组件调用父组件
{{total}}
<mime @increment="incrementTotal"></mime>
<template id="myInput">
<button @click="add">{{counter}}</button>
</template>
...
<script>
....
data:{
tatal: 0
},
methods:{
incrementTotal:function(){
this.total +=1;
}
},
components:{
data : function(){
return:{
counter : 0
}
},
methods : {
add : function(){
this.counter +=1;
this.$emit('increment'); //子组件通过 $emit触发父组件的方法 increment 还可以传参 this.$emit('increment' ,this.counter);
}
}
}
</script>
父组件调用子组件
<mime ref="child"></mime>
<button type="button" @click="clickref">调用子组件</button>
<template id="myInput">
<button @click="add">{{counter}}</button>
</template>
...
<script>
....
methods:{
clickref:function(){
var child = this.$refs.child; //获取子组件实例
child.counter = 45; //改变子组件数据
child.add(11); //调用子组件方法 add
}
},
components:{
data : function(){
return:{
counter : 0
}
},
methods : {
add : function(num){
this.counter +=1;
console.log('接受父组件的值:',num) //num为11
}
}
}
</script>
组件间互调
//新建一个空的
var bus = new Vue()
// 触发组件 A 中的事件
bus.$emit('id-selected', 1)
// 在组件 B 创建的钩子中监听事件
bus.$on('id-selected', function (id) {
// ...
})
总结: 太繁琐,直接用Vuex