组件 demo测试:
<template>
<view>
<view>
这是测试组件{{name}}
这是父组件传过来的数据{{title}} 地址:{{address}}
<button type="warn" @click="sendNum">给父组件传值</button>
</view>
</view>
</template>
<script>
export default{
data(){
return{
name:"zhangsan",
intId:null,
num:10
}
},
props:['title','address'],
beforeCreate() {
console.log("实例已经开始初始化了,不能拿到数据 ,顺序4",this.name)
},
created() {
console.log("初始化完成,可以拿到数据 ,顺序5",this.name);
this.intId=setInterval(()=>{
console.log("执行定时器");
},1000)
},
beforeMount() {
console.log("还未挂载,获取不了属性 ,顺序6");
},
mounted() {
console.log("挂载完成,可以拿到属性 ,顺序7");
},
destroyed() {
console.log("组件销毁");
clearInterval(this.intId);
},
methods:{
sendNum(){
console.log("给父级传值");
this.$emit("myEvent",this.num);//触发当前事列上的事件,可以进行传值
}
}
}
</script>
<style>
</style>
兄弟组件:
<template>
<view>
这是a组件:<button @click="addnum">修改b组件的数据</button>
</view>
</template>
<script>
export default{
data(){
return{
}
},
methods:{
addnum(){
uni.$emit("updateNum",12);//接收传递过来的数据
}
}
}
</script>
<style>
</style>
<template>
<view>这是b组件的数据:{{number}}</view>
</template>
<script>
export default{
data(){
return{
number:0
}
},
created() {
//监听全局的自定义事件,事件由 uni.$emit 触发,回调函数会接收事件触发函数的传入参数。
uni.$on("updateNum",num=>{
console.log(num)
this.number=num
})
}
}
</script>
<style>
</style>
进行测试:
<template>
<view>
<demo_test v-if="flag" :title="title" :address="address" @myEvent="getNum"></demo_test>
<button type="primary" v-on:click="checktest">切换test组件</button>
<text v-if="num!=0">这是组件传过来的值{{num}}</text>
<test_a></test_a>
<test_b></test_b>
</view>
</template>
<script>
import test from "@/components/test/demo_test.vue"
import testa from "@/components/test/a.vue"
import testb from "@/components/test/b.vue"
export default{
data(){
return{
flag:true,
title:"uni-app",
address:"北京城",
num:0
}
},
onLoad(pages) {
console.log("页面加载了 ,顺序2"+pages)
},
onShow() {
console.log("页面显示了 ,顺序3")
},
onReady() {
console.log("页面初次渲染完成了 ,顺序8");
},
onHide() {
console.log("页面被隐藏了,顺序1");
},
methods:{
checktest(){
this.flag=!this.flag;
},
getNum(num){
console.log(num);
this.num=num;
}
},
components:{
"demo_test":test,
"test_a":testa,
"test_b":testb
}
}
</script>
<style>
</style>
效果: