Uni-app 封装组件中点击事件回传父组件及传值

今天封装了一个组件,在组件中有个按钮点击事件要回传给父类,并执行响应操作。

组件中的回传类似iOS中的block,代理回调。
this.$emit("func_name", data)
func_name 要和父级页面中“@”绑定的名字一致。
this.emit 在组件内触发全局的自定义事件

<template name="titleBox">
    <view class="p_title">
        <text>{{p_title}}</text>
        <text @click="more()" class="p_more">{{p_more}}</text>
    </view>
</template>

<script>
export default{
    name:"titleBox",
    props:{
        p_title:{
            type: String,
            default: ''
        },
        p_more:{
            type: String,
            default: ''
        }
    },
    data(){
        return{
            
        }
    },
    methods:{
        more() {
            console.log('我是子组件')
            this.$emit('moreBtn',this.p_more) //(父组件中触发的事件名,要传的变量名)
        }
    }
}       
</script>

<style lang="scss">
.p_title{
    font-size: $uni-font-size-lg;
    color: $uni-color-error;
    padding-bottom:$uni-spacing-row-base;
    text{
        width: 70%;
        display: inline-block;
        font-weight: bold;
    }
    .p_more{
        font-size: $uni-font-size-sm;
        color: $uni-text-color-placeholder;
        width: 30%;
        text-align: right;
        font-weight: normal;
    }
}
</style>

父页面引入:

<titleBox :p_title="publicTitle" :p_more="publicMore" @moreBtn="publicmoreUrl"></titleBox>

publicTitle:'限时抢购',
publicMore:'逛一逛',

publicmoreUrl(e){
    uni.navigateTo({
        url:"/pages/details/index",
    });
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容