一、子组件和父组件之间的传参
1、引入子组件页面
import test from '../../components/test.vue'
2、在主页面的components
中定义test
组件
components: {
// 定义各个页面的组件,使子页面能在主页面显示
// test:test,键和值一样,只写test就是了
//定义组件,<test> </test>
test,
//定义组件,<test-a> </test-a>
"test-a":testA,
//定义组件,<test-b> </test-b>
"test-b":testB
}
<test v-if="flag" :title="title" @myEven='getNum'></test>
这是子组件传过来的参数 {{num}}
3、定义方法
getNum(num) {
console.log(num)
this.num = num
}
4、子组件相关代码
<view id="myView">
这是一个test组件 {{num}}
这是父组件传过来的数据 {{title}}
<button type="default" @click="sendNum">给父组件传值</button>
</view>
data() {
return {
num: 3,
intId:null
};
},
//接收父组件传过来的参数
props: ['title'],
methods: {
sendNum() {
console.log('给父组件传值')
this.$emit('myEven',this.num)
}
},
二、a组件修改b组件中的数据
1、在主页的components
中定义组件
components: {
// 定义各个页面的组件,使子页面能在主页面显示
// test:test,键和值一样,只写test就是了
//定义组件,<test> </test>
test,
//定义组件,<test-a> </test-a>
"test-a":testA,
//定义组件,<test-b> </test-b>
"test-b":testB
}
2、在主页中引入定义好的组件
import testA from '../../components/a.vue'
import testB from '../../components/b.vue'
3、a组件中的代码如下
<template>
<view>
这是a组件:<button type="default" @click='addNum'>修改b组件的数据</button>
</view>
</template>
<script>
export default {
name:"a",
data() {
return {
};
},
methods: {
addNum(){
//获取b组件中的数据
uni.$emit('updateNum',10)
}
}
}
</script>
4、b组件中的代码如下
<template>
<view>
这是b组件的数据: {{num}}
</view>
</template>
<script>
export default {
name:"b",
data() {
return {
num: 0
};
},
//页面初始化就执行给方法
created() {
uni.$on('updateNum',num=>{
this.num+=num
})
}
}
</script>