From parent to child:
parent component:
<template>
<view :title=”title”>
</view>
</template>`在这里插入代码片`
<script>
export default {
name: 'app',
data () {
return {
title: ‘我是父组件’
}
}
}
</script>
Sub-components: receive through props
<template>
<view>
这是父组件传递过来的数据{title}
</view>
</template>
<script>
export default {
name: 'app',
data () {
return {
}
},
props:[‘title’],
}
</script>
Pass from child to parent: (by triggering $emit)
child component:
<
template>
<view>
<button @click=”send()”>给父组件传值</button>
</view>
</template>
<script>
export default {
name: 'app',
data () {
return {
num: 66
}
},
methods:{
send(){
console.log(‘给父组件传值了’)
this.$emit(‘myEmit’,this.num)//第一个参数是自定义事件,第二个参数是你想传递的值
}
}
}
</script>
Parent component: A custom event is defined in the child component, and the parent component must use it where it needs to be used
<template>
<view @myEmit=”getNum”>
这是子组件传递过来的值{
{num}}
</view>
</template>
<script>
export default {
name: 'app',
data () {
return {
num: 0 // 也可以把子组件传递过来的值存储起来,默认是0 ,传值过后值发生改变
}
},
methods:{
// 通过形参接收子组件传递过来的值
getNun(num){
console.log(num)
this.num = num
}
}
}
</script>
Brother component pass value:
brother a component
<template>
<view>
<button @click=”addNum()”>我要修改兄弟b组件中的数据</button>
</view>
</template>
<script>
export default {
name: 'app',
data () {
return {
}
},
methods:{
// 通过全局$emit 去触发b组件中的回调函数updateNum,同时还可以传递参数
addNum(){
uni.$emit(‘updateNum’, 10)
}
}
}
</script>
Brother b component:
<template>
<view>
这是b中的数据{
{num}}
</view>
</template>
<script>
export default {
name: 'app',
data () {
return {
num:66
}
},
Created(){
uni.$on(‘updateNum’,num = >{
this.num + = num
})
}
methods:{
}
}
</script>