uni组件之间的各种传值方式
1、先建立一个父组件 parent.vue,定义一个变量和一个数组,把它传递给子组件,代码如下:
<template>
<view>
<testchild :title="title" :array="array" ></testchild>
</view>
</template>
<script>
import testchild from '../../components/testchild.vue'
export default{
data(){
return{
title:"123",
array:[
{id:"1",name:"xiaoming"},
{id:"2",name:"xiaoming1"},
{id:"3",name:"xiaoming2"},
]
}
},
onLoad() {
},
components:{
testchild,
},
methods:{
}
}
</script>
<style>
</style>
2、新建testchild子组件,接收父组件的值和数组,代码如下:
<template>
<view >
<text>父组件的值:{{title}}</text>
<view>从父组件获取到得数据:</view>
<view v-for="item in array" :key="item.id">
<text>{{item.name}}</text>
</view>
</view>
</template>
<script>
export default{
data(){
return{
}
},
onLoad() {
},
props:['title','array'],
}
</script>
<style>
</style>
3、如图所示,子组件获取到了父组件的数据:

4、父组件获取子组件的数据,子组件代码如下:
<template>
<view >
<button type="default" @click="parentValue">给父组件传值</button>
</view>
</template>
<script>
export default{
data(){
return{
name:'张三',
}
},
onLoad() {
// console.log()
},
methods:{
parentValue(){
this.$emit('myEven',this.name)
}
}
}
</script>
<style>
</style>
5、父组件的代码如下:
<template>
<view >
<text>从子组件获取到得数据:{{name}}</text>
<testchild @myEven="getchild" ></testchild>
</view>
</template>
<script>
import testchild from '../../components/testchild.vue'
export default{
data(){
return{
name:''
}
},
onLoad() {
},
components:{
testchild,
},
methods:{
//这里得参数按照子组件传参的顺序
getchild(name){
console.log(name);
this.name = name;
}
}
}
</script>
<style>
</style>
6、如图所示,父组件得到子组件的数据:

7、我们尝试新建一个父组件parent,在这里引用两个组件,实现这两个组件之间的传值,父组件代码:
<template>
<view >
<test-a></test-a>
<test-b></test-b>
</view>
</template>
<script>
import testA from '../../components/a.vue'
import testB from '../../components/b.vue'
export default{
data(){
return{
}
},
onLoad() {
},
components:{
'test-a':testA,
'test-b':testB,
},
methods:{
}
}
</script>
<style>
</style>
8、我们新建一个a.vue,代码如下:
<template>
<view class="">
<text>这是a组件</text>
<button type="default" @click="updateValue">修改b组件的值</button>
</view>
</template>
<script>
export default {
data(){
return{
}
},
methods:{
updateValue(){
uni.$emit('updataVal',"李四")
}
}
}
</script>
<style>
</style>
9、新建一个b.vue,代码如下:
<template>
<view class="">
这是b组件,值为{{value}}
</view>
</template>
<script>
export default {
data(){
return{
value:'张三'
}
},
methods:{
},
created() {
uni.$on('updataVal',data=>{
console.log(data);
this.value = data;
})
}
}
</script>
<style>
</style>
10、我们来点击一下a组件,可以发现b组件的值被a组件改变了。这就是两个子组件之间的传值方式,条件(必须同时引入同个页面)


11、如果组件之间没有任何关系,可以定义全局组件bus来改变值,或者使用vuex同样也能达到效果。

浙公网安备 33010602011771号