提示:以下是本篇文章正文内容,下面案例可供参考
一、结果图
二、父子组件之间的传值
父组件:
<template>
<view class="test_wrapp">
<view class="father_son">
<view>父子之间传值</view>
<value-c :fatherNum="fatherNum" @updateSon="updateSon"></value-c>
</view>
</view>
</template>
<script>
import valueC from '../../components/valueC'
export default {
components: {
valueC
},
data() {
return {
fatherNum: 0
}
},
methods: {
// 子传过来的值
updateSon(num) {
this.$data.fatherNum += num
}
}
}
</script>
<style lang="scss" scoped>
.father_son{
padding: 30rpx 0;
margin-bottom: 30rpx;
border: 1rpx solid #ddd;
}
</style>
子组件:
<template>
<view>
<view>我是子呀,接收我父给我的值:{{fatherNum}}</view>
<button @click="sendSon">子来修改父值了</button>
<view>我是子呀,传值回给我的父值:{{fatherNum}}</view>
</view>
</template>
<script>
export default {
props: ["fatherNum"],
data() {
return {}
},
methods: {
// 调用父组件方法
sendSon() {
this.$emit("updateSon", 2)
}
}
}
</script>
<style lang="scss" scoped>
</style>
三、兄弟组件之间传值
兄弟A组件:
<template>
<view>
<button @click="sendNum">我是小A</button>
</view>
</template>
<script>
export default {
data() {
return { }
},
methods: {
sendNum() {
uni.$emit('update', 10)
}
}
}
</script>
<style lang="scss" scoped>
</style>
兄弟B组件:
<template>
<view>
<view>我是小B,接收我兄弟小A的值:{{numCount}}</view>
</view>
</template>
<script>
export default {
data() {
return {
numCount: 0
}
},
created() {
uni.$on('update', num => {
this.$data.numCount += num
})
}
}
</script>
<style lang="scss" scoped>
</style>
父组件:
<template>
<view class="test_wrapp">
<view class="brother_item">
<view>兄弟之间传值</view>
<value-a></value-a>
<value-b></value-b>
</view>
</view>
</template>
<script>
import valueA from '../../components/valueA'
import valueB from '../../components/valueB'
export default {
components: {
valueA,
valueB
},
data() {
return {}
},
methods: { }
}
</script>
<style lang="scss" scoped>
.brother_item{
padding: 30rpx 0;
border: 1rpx solid #ddd;
}
</style>