组件内部事 ,件如何传递给父级组件
1.子组件定义
<template>
<view>
<h1 @click="tap1">{{title}}</h1>
<div>{{content}}</div>
</view>
</template>
<script>
export default {
props:{
title : {
type : String,
default : ""
},
content : {
type : String,
default : ""
}
},
data() {
return {
};
},
watch:{
title : function (newVal, oldVal) {
console.log(newVal, oldVal);
}
},
methods:{ //标题的@click点击事件,触发此函数
tap1 : function(){
console.log("子组件内部方法tap1");
this.$emit('tap1', this.title) //$emit('事件的名称',参数),绿底必须和绿底名称一致,橙色的底色不一定要和绿色底一致
}
}
}
</script>
<style>
</style>
2.父组件
<template>
<view class="">
<mycomponent :title="title" content="content...." @tap1="tap"></mycomponent>
//1.监听子组件传来父组件的方法@tap1监听子组件传递过来的函数。tap1必须和this.$emit('tap1', this.title)中的第一个参数名字相同
</view>
</template>
<script>
import uniNumberBox from "@/components/uni-number-box/uni-number-box.vue"
import mycomponent from "@/components/mycomponent.vue"
export default {
data() {
return {
title : "新闻标题"
}
},
onLoad:function(){
var _self = this;
setTimeout(function() {
_self.title = "hi123"
}, 3000);
},
methods:{
tap : function (e) {//2.通过e可接受到子组件传递给父组件的参数
console.log("父组件tap方法")
}
},
components: {
uniNumberBox,
mycomponent
}
}
</script>
<style lang="less">
@import "../../less.less";
</style>
注意:子组件中的
this.$emit('tap1', this.title) //$emit('事件的名称',参数) 事件名称必须和
父组件中的@函数名一致
<mycomponent :title="title" content="content...." @tap1="tap"></mycomponent>
浙公网安备 33010602011771号