7. UniAPP カスタム コンポーネントと通信
(1) カスタムコンポーネントのコンセプト
コンポーネントは
vue
テクノロジー.コンポーネントにより、UI関連のホイールの製造と共有が容易になり、vueユーザーの開発効率が大幅に向上します.component
コンポーネントをプロジェクトディレクトリに保存し、単一uni-app
ファイルコンポーネント(.vueコンポーネント)のみをサポートします.vue
コンポーネントは、「グローバル登録」と「ページのインポート」の 2 つの方法で使用できます。使用は次の 3 つのステップに分けられます。
輸入
import xxx from 'xxx'
登録
Vue.use('xx',xx)
components:{ xxx }
使用
<xx />
新しいサブコンポーネント
<template>
<view>
<text class="red">子组件</text>
<view>{
{msg}}</view>
<view>
<button @click="sayHelloToFather">按钮</button>
</view>
</view>
</template>
<script>
export default {
props:['msg'],
data() {
return {
};
},
methods:{
sayHelloToFather(){
this.$emit('childEvent','子组件传递给父页面的信息')
//uni.$emit('getInfo', '樱桃小丸子')
}
}
}
</script>
<style scoped>
.red{
color: red;
}
</style>
親ページは子コンポーネントをインポートします
<template>
<view class="content">
<text>父页面</text>
、
<child :msg="title" @childEvent="sayHello"></child>
</view>
</template>
<script>
import Child from '@/components/child.vue'
export default {
data() {
return {
title: '我是父组件定义的数据信息'
}
},
components:{
Child
},
onShow(){
console.log('Index page show')
},
onLoad() {
console.log(getCurrentPages())
},
onPullDownRefresh(){
console.log('页面下拉刷新了')
},
methods: {
sayHello(msg){
this.title = msg
}
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
}
</style>
(2) 親子コンポーネント通信
- 親コンポーネントは、カスタム プロパティを介して子コンポーネントにデータを渡します。
- 子コンポーネントは、親コンポーネントから
props
渡さ
- 親コンポーネントは、カスタム イベント タグを介して子コンポーネントにイベントを渡します
- 子コンポーネントは、親コンポーネントによって定義されたイベントをトリガーすることにより、親コンポーネントのデータを変更します
<child :msg="title" @childEvent="sayHello"></child>
(3) スロットデータ配布とスコープスロット
- 親コンポーネントは、子
slot
コンポーネント内のネストされた html コンテンツを呼び出すことにより、子コンポーネントに配布します- 子コンポーネントは、
slot
タグ
Vue はコンテンツ配信用の一連の API を実装し、slot
要素を。
次のようなコンポーネントを構成できます。
<template>
<view>
<componentA>
Your Profile
</componentA>
</view>
</template>
<componentA>
のテンプレートでは、次のように記述できます。
<template>
<view>
<!-- 我是子组件componentA -->
<view >{
{title}}</view>
<slot></slot>
</view>
</template>
コンポーネントがレンダリングされると、<slot></slot>
「Your Profile」に置き換えられます。スロットには、以下を含む任意のテンプレート コードを含めることができますHTML
。
<template>
<view>
<!-- 我是父组件 -->
<componentA>
<view>Your Profile</view>
<!-- 添加一个 uni-icons 图标 -->
<uni-icons type="contact" size="30"></uni-icons>
</componentA>
</view>
</template>
<componentA>
of に要素がtemplate
含まれていない場合、コンポーネントの開始タグと終了タグの間のコンテンツはすべて破棄されます。<slot>
(4) グローバルイベントの定義と通信
- アプリケーションのどこでも使用できる
uni.$on
グローバル イベントを作成する- アプリケーション全体のどこでも使用して、グローバルイベント
uni.$emit
を
グローバル イベントを作成する
<template>
<view>
<text>我</text>
<text>{
{name}}</text>
</view>
</template>
<script>
export default {
data() {
return {
name: 'aaaa'
}
},
onLoad(){
uni.$on('getInfo', name =>{
uni.showToast({
icon:'none',
title: '全局事件被触发了',
duration: 2000
});
//console.log('Me 页面中的全局事件被触发了')
this.name = name
})
},
methods: {
}
}
</script>
<style>
</style>
トリガーイベント
<script>
export default {
data() {
return {
};
},
methods:{
sayHelloToFather(){
uni.$emit('getInfo', '张三')
}
}
}
</script>