在uni-app中,可以通過創建一個后綴名為vue的文件,即創建一個組件成功,其他組件可以將該組件通過impot的方式導入,在通過components進行注冊即可
使用方式和生命周期跟vue一樣,具體參考
使用:https://www.cnblogs.com/makalochen/p/13870097.html
單文件組件:https://cn.vuejs.org/v2/guide/single-file-components.html#ad
生命周期:https://cn.vuejs.org/v2/api/#選項-生命周期鈎子
這里給出一個示例
基本使用示例
創建組件
創建test組件,在component中新建test.vue文件,內容如下
<template>
<view>
這是一個自定義組件
</view>
</template>
<script>
</script>
<style>
</style>
其他組件中導入該組件並注冊和使用
導入
import test from '../../components/test.vue';
注冊
comments:{
test : test
}
使用
<test></test>
完整示例
<template>
<view>
<test></test>
</view>
</template>
<script>
import test from '../../components/test.vue';
export default{
components:{
test:test
}
}
</script>
<style>
</style>
效果

組件之間傳值
https://cn.vuejs.org/v2/guide/components-props.html
父組件給子組件傳值
https://cn.vuejs.org/v2/guide/components-props.html#傳遞靜態或動態-Prop
組件定義中,通過props來接受外界傳遞到組件內部的值
<template>
<view>
這是一個自定義組件 {{msg}}
</view>
</template>
<script>
export default {
props: ['msg']
}
</script>
<style>
</style>
其他組件在使用test組件的時候,使用屬性綁定,傳遞值
<template>
<view>
<!-- 屬性綁定 -->
<test :msg="msg"></test>
</view>
</template>
<script>
import test from "../../components/test.vue"
export default {
data() {
return {
msg: 'hello'
}
},
//組件注冊
components: {
test
}
}
</script>

子組件給父組件傳值
https://cn.vuejs.org/v2/guide/components.html#監聽子組件事件
定義組件通過$emit觸發事件進行傳遞參數
<template>
<view>
<button type="primary" @click="sendMsg">給父組件傳值</button>
</view>
</template>
<script>
export default {
data () {
return {
status: '子組件給父組件傳值'
}
},
methods: {
sendMsg () {
this.$emit('myEvent',this.status)
}
}
}
</script>
父組件中定義自定義事件並接收參數
<template>
<view>
<test @myEvent="getMsg"></test>
</view>
</template>
<script>
import test from "../../components/test.vue"
export default {
methods: {
getMsg (res) {
console.log(res)
}
},
components: {test}
}
</script>
兄弟組件之間的傳值
uni-app的頁面通訊
https://uniapp.dcloud.io/collocation/frame/communication
vue的實現
https://cn.vuejs.org/v2/api/#實例方法-事件
這里因為是uni-app,所以還是使用uni-app官方的
定義a組件
<template>
<view>
這是a組件:<button @click="addNum">修改b組件的數據</button>
</view>
</template>
<script>
export default {
data() {
return {
};
},
methods: {
addNum () {
//觸發全局的updateNum事件
uni.$emit('updateNum',10);
}
}
}
</script>
<style>
</style>
定義b組件
<template>
<view>
這是b組件的數據:{{num}}
</view>
</template>
<script>
export default {
data() {
return {
num: 0
};
},
//組件創建的時候觸發
created(){
//監聽全局的updateNum事件
uni.$on('updateNum', num => {
this.num += num
})
}
}
</script>
<style>
</style>

實現了點擊修改b組件數據的功能

