此文为uni-app 总结笔记(16)— 组件的通讯,父传子,子传父,兄弟组件 官方API文档
父组件给子组件传值
子组件通过props来接受外界传递到组件内部的值
子组件代码演示:test.vue
<template>
<view>
是父组件传过来的值 {
{title}}
</view>
</template>
<script>
export default {
props: ['title']
}
</script>
<style>
</style>
父组件代码演示: index.vue
<template>
<view>
<test :title="title"></test>
</view>
</template>
<script>
import test from "@/components/test/test.vue"
export default {
data () {
return {
msg: 'hello我是父组件'
}
},
components: {test}
}
</script>
子组件给父组件传值
通过$emit触发事件进行传递参数 test.vue
<template>
<view>
<view>这是父组件传过来的值{
{title}}</view>
<button @click="sendNum">给父组件传值</button>
</view>
</template>
<script>
export default {
data () {
return {
num: 3
}
},
methods: {
sendNum() {
console.log("给父组件传值啦")
this.$emit("myEven",this.num)
}
},
}
</script>
父组件定义自定义事件并接收参数 index.vue
<template>
<view>
<test :title=title @myEven="getNum"></test>
<view>这是子组件传过来的值{
{num}}</view>
</view>
</template>
<script>
import test from "@/components/test/test.vue"
export default {
data () {
return {
num: 0
}
},
methods: {
getNum(num) {
console.log(num)
this.num = num
}
},
components: {
test}