uni-app组件之间的通讯--父子/兄弟组件之间传递数据 - 走看看
1、父子间传递数据
父:
<template>
<view>
<test v-if="flag" :title="title" @myEven="getNum"></test>
<test-a></test-a>
<test-b></test-b>
</view>
</template>
<script>
import test from "../../components/test.vue";
import testA from "../../components/a.vue";
import testB from "../../components/b.vue";
export default {
data() {
return {
title: "hello",
flag: true
}
},
methods: {
checkTest() {
this.flag = !this.flag;
},
getNum(number) {
console.log(number);
}
},
components: {
test, //testa:test
"test-a": testA,
"test-b": testB
}
}
</script>
子:
<template>
<view>
<view>这是父组件传过来的数据{{title}}</view>
<button type="default" @click="sendNum">获取num</button>
</view>
</template>
<script>
export default {
data() {
return {
num: 3,
}
},
props: ["title"],
methods: {
sendNum() {
this.$emit('myEven', this.num);
}
}
}
</script>
2、兄弟间传输数据:
a.vue:
<template>
<view>
这是a组件:<button @click="addNum">修改b组件的数据</button>
</view>
</template>
<script>
export default{
data(){
return{
}
},
methods:{
addNum(){
uni.$emit("updataNum",10);
}
}
}
</script>
b.vue:
<template>
<view>
这是b组件的数据:{{num}}
</view>
</template>
<script>
export default {
data() {
return {
num: 0
}
},
created() {
uni.$on("updataNum", num => {
this.num += num;
});
}
}
</script>
总结:通过uni.$on声明事件,通过uni.$emit调用事件。
也可以通过props["变量名"]来进行声明。