父传子(左边是子组件,右边是父组件)
子传父(左边是子组件,右边是父组件)
子父传参代码
子组件:
<template>
<view>
这是test组件··
<view id="myview">
给它引入到通讯录中{{num}}
</view>
<view style="color: #f00;">
我是子组件我接收:
<text style="color: #87b58b;">{{title}}</text>
</view>
<button type="default" @click="chuanzhi">点击给父组件传值</button>
</view>
</template>
<script>
export default {
name: "test",
data() {
return {
num: 3,
dingshiqi: null
};
},
methods:{
// 给父组件传值
chuanzhi(){
console.log('要给父组件传值')
// 第一个参数要去触发自定义事件
this.$emit('event',this.num)
}
},
props: ['title'],
// 实例已经开始初始化了,但是数据还没有初始化完成,包括页面也没有开始渲染
beforeCreate() {
console.log('实例已经开始初始化了')
console.log(this.num) //undefined
},
// 可以拿到数据,包括被定义的方法
created() {
console.log('实例已经创建完成了')
console.log(this.num) //3
// 给定时器赋值为空组件在销毁时,就不会再执行定时器
this.dingshiqi = setInterval(() => {
console.log('1秒钟执行一次定时器')
}, 1000)
},
// 数据能够渲染在页面上,组件还没有
beforeMount() {
// console.log('beforeMount', document.getElementById('myview'))
console.log(this.num) //3
},
// 组件渲染到页面上
mounted() {
// console.log('mounted', document.getElementById('myview'))
console.log(this.num) //3
},
destroyed() {
console.log('destroyed组件销毁')
// 在组件销毁时,清除定时器
clearInterval(this.dingshiqi)
}
}
</script>
<style>
</style>
父组件:
<template>
<view>
<!-- 因为在要在子组件传参,得写在子组件里 -->
<!-- 形参要在组件里面定义,注册自定义事件 -->
<test v-if="flag" :title="title" @event="getNum"></test>
<button type="primary" @click="qiehuan" v-if="!flag">显示test组件</button>
<button type="primary" @click="qiehuan2" v-if="flag">隐藏test组件</button>
<view style="color: #f00;">
<!-- 记得保存一下传过来的值,直接调用会报错 -->
我接收到了由子组件传递过来的参数:<text style="color: #0eb4bd;">{{num}}</text>
</view>
</view>
</template>
<script>
import test from '../../components/test.vue'
export default {
data() {
return {
// 组件间通讯:父传子
// 传递title值
title: '我是父组件',
flag: true,
num:null
}
},
components: {
test
},
methods: {
// 形参接收
getNum(res){
console.log('我接收到了')
// 接收参数
console.log(res)
this.num=res
},
qiehuan() {
this.flag = true
},
qiehuan2() {
this.flag = false
}
}
}
</script>
<style>
</style>
兄弟之间
通过 uni.$on(eventName,callback)监听全局的自定义事件。
通过uni.$emit(eventName,OBJECT)触发全局的自定义事件。