组件之间传递参数
大约 1 分钟
组件之间传递参数
$on,$emit,$off
在页面与页面之间通讯时,很多人会直接选择使用在navigato的时候直接拼接字符串来传递。可是当需要传依个比较多数据的的对象的时候这个方式就不是很管用了,为此uniapp给我们提供了页面与页面之间通讯的极为简便的方法。
比如我在下订单页面的时候需要用户选择一个地址去配送,因此我们需要点击之后跳转到选择收货地址页面。而在选择完了收货地址以后需要关闭那个页面返回该订单页面。因此在该订单页面我们需要开启监听用户选择地址的事件。注意在订单页面卸载的时候也要记得关闭该监听。
下面为订单页面的代码:
onLoad() {
//开启监听选择收货地址事件
uni.$on('choosePath',(res)=>{
this.path = res;
})
},
//页面卸载
onUnload() {
//关闭监听选择收货地址事件
uni.$off('choosePath',()=>{
console.log('关闭监听选择收货地址');
})
},
methods: {
openPathList(){
uni.navigateTo({
url: '../user-path-list/user-path-list?type=choose'
});
},
}
下面是选择地址的页面:
onLoad(option) {
if(option.type==='choose'){
this.isChoose = true
}
},
methods:{
//选择收获地址
choosePath(item){
if(this.isChoose){
//通知订单页面修改地址
uni.$emit('choosePath',item)
//关闭当前页面
uni.navigateBack({
delta: 1
});
}
}
}
跨级组件传递状态
使用 Provide Inject 选项 父组件中:
<template>
<Demo :msg="msg"></Demo>
</template>
<script>
export default {
provide(){
return {
handleClick: () => {
// do something
}
}
}
};
子组件中:
<template>
<div>
<el-button @click="handleClick"> </el-button>
</div>
</template>
<script>
export default {
name: "DEMO",
inject: ["handleClick"],
data() {
return {};
},
};
</script>