vue-子组件向父组件传值
1.在子组件里面定义,子组件用 $emit() 触发事件,$emit() 第一个参数为 自定义的事件名称 第二个参数为需要传递的数据
this.$emit('myEvent',value)
2.在父组件里面通过在组件里设置,父组件用v-on 监听子组件的事件,@myEvent 是子组件中$emit 定义传触发事件名称,getValue是事件源,定义在父组件当中;
@myEvent="getValue"
3.在父组件method方法里面定义
getValue(value){
console.log('value',value) //取值
}
实例:
定义根组件
<!-- 定义根组件 --> <div id="app"> <a-father @father-text="fathers"></a-father> </div>
逻辑代码:
<script>
// 定义一个全局的子组件,a-father是new vue的子组件
Vue.component('a-father',{
template: `<div>
// 这里的是子组件a-son组件,@enlarge-text事件是子组件$emit触发的自定义事件名称,handle才是事件源,handle函数定义在父组件的methods里面;子组件只能在父组件模板里面使用,
<a-son @enlarge-text="handle"></a-son>
<button @click='$emit("father-text", "父组件")'>父组件</button>
</div>`,
data: function() {
return{
}
},
methods:{
//handle函数才是事件源,handle函数必须定义在父组件中
handle(a){
console.log(a); //参数a为子组件传递的参数
}
},
components:{
'a-son':{
// 子组件定义一个按钮,$emit()会触发里面定义的enlarge-text自定义事件,第二个为传递的参数;
template:`<div><button @click='$emit("enlarge-text", 5)'>扩大父组件中字体大小</button></div>`,
data:function(){
return{
}
}
}
}
})
const vm = new Vue({
el:'#app',
data: {
msg:'vue'
},
methods:{
fathers(a){
console.log(a);
}
}
})
</script>
时间如白驹过隙,忽然而已,且行且珍惜......
浙公网安备 33010602011771号