使用组件可以减少代码的重复率,提高写代码的效率,改起来也方便。
最近在使用uni-app做项目,一套代码多端实现,做些简单的项目还是可以的。废话少说,说说子组件向父组件传值。
子组件获取到值的时候,使用$emit传给父组件:
this.$emit("getChild1",this.list);
父组件首先引入子组件:
import child1 from './child1'
注册子组件:
components: {
child1,
child2
},
然后可以使用子组件:
<child1 @getChild1 = "getChild1" v-if="current==0"></child1>
注意,子组件的提交的函数名,和父组件里使用子组件@后的名字是一样的。
但是要注意:子组件获取数据的函数要在created(){}里面获取,这个坑,要注意!!
在methods里可以获取到子组件的数据:
getChild1(e){
console.log(e)
},
效果大概就是这样:
代码我也贴出来好了:
首页是,目录结构:
res.json:
{
"code": 100,
"fruitData": [
"西红柿",
"黄瓜",
"苹果"
],
"filmData": [
"西红柿首富",
"101次求婚",
"肖申克的救赎"
]
}
child1:
<template>
<view class="content">
<view v-for="(item,index) in list" :key="index">{{item}}</view>
</view>
</template>
<script>
export default {
data() {
return {
list: []
}
},
components: {
},
onLoad() {},
created() {
var data = require('../../static/res.json')
this.list = data.fruitData
this.$emit("getChild1",this.list);
},
methods: {
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200upx;
width: 200upx;
margin-top: 200upx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50upx;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36upx;
color: #8f8f94;
}
</style>
child2:
<template>
<view class="content">
<view v-for="(item,index) in list" :key="index">{{item}}</view>
</view>
</template>
<script>
export default {
data() {
return {
list: []
}
},
components: {
},
onLoad() {},
created() {
var data = require('../../static/res.json')
this.list = data.filmData
this.$emit("getChild2",this.list);
},
methods: {
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200upx;
width: 200upx;
margin-top: 200upx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50upx;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36upx;
color: #8f8f94;
}
</style>
parent:
<template>
<view class="content">
<view class="btn-container">
<button @click="getData(index)" v-for="(item,index) in list" :key="index">{{item}}</button>
</view>
<child1 @getChild1 = "getChild1" v-if="current==0"></child1>
<child2 @getChild2 = "getChild2" v-if="current==1"></child2>
</view>
</template>
<script>
import child1 from './child1'
import child2 from './child2'
export default {
data() {
return {
list:[
'水果',
'电影'
],
current:0
}
},
onLoad() {
},
components: {
child1,
child2
},
methods: {
getData(index){
this.current = index
},
getChild1(e){
console.log(e)
},
getChild2(e){
console.log(e)
}
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.btn-container{
display: flex;
justify-content: space-between;
align-items: center;
}
</style>
大概就是这些。