uni-app學習-------子組件的創(chuàng)建及父子組件互相傳值
1.子組件的創(chuàng)建及父組件引用子組件
子組件的創(chuàng)建和父組件差不多。
父組件引用子組件迈螟,先導入子組件缚俏,在<script></script>內汁胆。import name(給子組件起個名字) from "子組件地址"
然后components:{ name},然后就可以在<template></template>內使用子組件了。
2.父組件傳值給子組件:
例:父組件<childs1 :text="text1" :text1="text" > </childs1>遵班,可以傳多個值屠升,:text為鍵="text1"為值,可設置多個狭郑。前面的冒號是v-bind的簡寫
子組件:在<script></script>用props接收腹暖,因為是數(shù)據(jù),可以解說多個翰萨。然后就可以直接用接收到的數(shù)據(jù)
3.子組件傳值給父組件
例:子組件:this.emit(鍵名,鍵值)
父組件:<childs1 @鍵名="方法名" </childs1>然后在方法中獲取值
方法名(res){this.value=res}
下面是例子
image
創(chuàng)建childs.vue
<template>
<view >
<view>{{text}}+{{text1}} </view>
<button @click="click1">點擊事件</button>
</view>
</template>
<script>
export default {
data(){
return{
value:"這是子組件的值"
}
},
props:["text","text1"],
methods:{
click1(){
this.$emit("change2",this.value)
}
}
}
</script>
<style>
</style>
image.gif
然后是父組件
<template>
<view>
<childs1 @change2="change1" :text="text1" :text1="text" > </childs1>
<view>111 + {{value}}</view>
</view>
</template>
<script>
import childs1 from "../../components/childs.vue"
export default {
components:{
childs1
},
data() {
return {
text:"我是父組件值1",
text1:"我是父組件值2",
value:''
}
},
methods: {
change1(res){
this.value = res
}
}
}
</script>
<style>
</style>