uniapp 学习笔记四 组件使用和参数传递事件触发
detail.vue
<template>
<view>
商品详情
<button type="primary" @tap="handleBack">返回上一页</button>
<button type="default" @tap="handleMy">返回个人页面</button>
<view class="">
<!-- 使用组件 -->
<my-comp v-for="(item,index) in 10" name="何仙姑"></my-comp>
</view>
</view>
</template>
<script>
/* 组件使用三步走 引入 注册 使用 */
import MyComp from '../../components/test-my-comp.vue';//引入
export default {
data() {
return {
}
},
components: {
'my-comp':MyComp //注册
},
methods: {
handleBack(){
uni.navigateBack({
delta:1
})
},
handleMy(){
/*
uni.navigateTo({ //不能跳转底部菜单页,只能跳转普通页面
url:'../home/home'
}) */
uni.switchTab({ //用于跳转底部菜单页
url:'../home/home'
})
// uni.redirectTo({
// // 重定向到页面
// url:'../home/home'
// })
}
},
onLoad(option) {
console.log(option);
console.log('onLoad 生命周期 执行');
},
onShow() {
console.log('onShow 生命周期 执行');
},
onHide() {
console.log('onHide 生命周期 执行');
},
onLaunch() {
console.log('onLaunch 生命周期 执行');
}
}
</script>
<style>
</style>
bread.vue
<template>
<view>
<view class="flex justify-between padding">
<view class="">
草莓蛋糕
</view>
<view class="">
购物车按钮{{num}}
</view>
</view>
<test-my-comp name="铁拐李" @onNum="handleNum"></test-my-comp>
</view>
</template>
<script>
import MyComp from '../../components/test-my-comp.vue';//引入
export default {
data() {
return {
num:100
}
},
methods: {
handleNum(n){//页面和组件通信,触发事件
console.log(n);
this.num += n;
}
},
components: {
'test-my-comp':MyComp //注册
}
}
</script>
<style lang="scss">
.cont{
display: flex;
flex-wrap: wrap;
padding: 15upx;
justify-content: space-between;
}
</style>
cake.vue
<template>
<view>
<view class="flex justify-between padding">
<view class="">
猫屎咖啡
</view>
<view class="">
牛奶拿铁
</view>
</view>
<view class="cont">
<view class="cake-item" v-for="(item,index) in 8" @tap="handleDetail(index)">
<view class="poster">
</view>
<view class="info-cont">
<view class="info">
<view class="fs-28">
黄油咖啡
</view>
<view class="fs-16">
Huangyou Coffee
</view>
<view class="fs-18">
<text class="fs-14">Y</text>
218.00
</view>
</view>
<view class="cart-btn">
</view>
</view>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
}
},
methods: {
handleDetail(idx){
console.log(idx);
uni.navigateTo({
url:'../detail/detail?idx='+idx
})
},
}
}
</script>
<style lang="scss">
.cont{
display: flex;
flex-wrap: wrap;
padding: 15upx;
justify-content: space-between;
}
.cake-item{
width: 350upx;
.poster{
height: 350upx;
background-color: #f5f5f5;
}
.fs-28{
font-size: 28upx;
margin-top: 24upx;
}
.fs-16{
font-size: 16upx;
margin: 14upx 0;
}
.fs-18{
font-size: 18upx;
margin-bottom: 22upx;
}
}
</style>
组件 test-my-comp.vue
<template>
<view @tap="handleNum">
测试公共组件 {{name}}
</view>
</template>
<script>
export default {
name:"test-my-comp",
props:['name'],
data() {
return {
};
},
created() {
console.log('created 生命周期 执行');
},
methods:{
handleNum(){//组件和页面通信,触发事件
this.$emit('onNum',10);
}
}
}
</script>
<style lang="scss">
</style>