前言:本篇文章主要講的是自定義組件的使用與傳參。在不同的頁面重複使用到相同或者類似的模塊,這裏就可以使用到組件就省略了不少代碼,不用每個頁面去寫相同的代碼,直接去引用該組件就可以了,下面以自定義頂部爲示例。
引入自定義頂部組件效果:
PS:父組件向子組件傳參使用的是props,後面可以看到打印出來的傳參。
子組件向父組件傳參效果:
PS:子組件向父組件使用的uni.$emit
目錄結構:
在pages.json關閉原生頂部:
父組件-index.vue
<template>
<view class="content">
<!-- 以標籤的方式載入,objdata是傳參對象 -->
<myheader :objdata="objdata"></myheader>
<!-- onval用來記錄子組件傳參 -->
<view style="padding: 20rpx 0;">子組件傳過來的值{{onval}}</view>
</view>
</template>
<script>
// 引入自定義組件
import myheader from "../../components/myheader.vue"
export default {
// 組件註冊
components:{
myheader
},
data() {
return {
objdata:{
type:0
},
onval:0
}
},
onUnload() {
uni.$off('thatComponents')
},
onLoad() {
uni.$on('thatComponents',(data)=>{
console.log(data);
this.onval+=data;
})
}
}
</script>
<style>
</style>
子組件-myheader.vue
<template>
<view>
<view style="width: 100%;text-align: center;background-color: #FD5C5C;color: white;font-size: 16px;height: 55px;line-height: 55px;">
首頁
</view>
<button type="default" @click="thatComponents">子組件傳參給父組件</button>
</view>
</template>
<script>
export default{
props:['objdata'],
data(){
return{
types:''
}
},
created:function(){
this.types=this.objdata.type;
console.log(this.objdata)//打印父組件傳過來的參數
console.log(this.types)
},
methods:{
thatComponents(){
uni.$emit('thatComponents',1)
}
}
}
</script>
<style>
</style>