1. 程式人生 > 其它 >【uni-app筆記整理十】元件的高階使用(uni元件【下】)

【uni-app筆記整理十】元件的高階使用(uni元件【下】)

技術標籤:uni-appvuejsjavascriptuni-app元件

版權宣告:本文為 小異常 原創文章,非商用自由轉載-保持署名-註明出處,謝謝!
本文網址:https://sunkuan.blog.csdn.net/article/details/111684560

文章目錄







在之前的部落格中,我們已經講解過 《uni元件的基本使用》

,本篇部落格中我們著重講解 如何建立元件元件的生命週期元件之間如何通訊 以及 uni 元件庫的使用


一、元件的建立

uni-app 中,可以通過建立一個字尾名為 .vue 的檔案,這個檔案就是一個元件。若在其他元件中使用該元件,可以通過 import 的方式匯入,再通過當前介面中的 components 屬性進行註冊即可。
 
下面我以一個小案例帶領大家建立一個自定義的元件:

1、建立元件

components 目錄中建立 login 目錄,然後在 login 目錄中新建 login.vue 檔案,檔案內容如下:

<template>
	<view
>
這是一個元件</view> </template> <script></script> <style></style>

2、匯入元件

在需要引入的元件中匯入該元件:

import login from "@/component/test/test.vue"

3、註冊元件

...
method: { },
component: {
	login
}

4、使用元件

<login></login>


二、元件的生命週期

元件的生命週期Vue 例項的生命週期 一樣,在這裡我不作過多敘述,感興趣的小夥伴可以參考我之前寫的部落格:

《Vue 生命週期》



三、元件之間的通訊

  • uni.$emit(eventName, OBJECT):觸發全域性的自定事件。附加引數都會傳給監聽器回撥。

    • eventName:型別是 String,事件名;
    • OBJECT:型別是 Object,觸發事件攜帶的附加引數。
  • uni.$on(eventName,callback):監聽全域性的自定義事件。事件可以由 uni.$emit 觸發,回撥函式會接收所有傳入事件觸發函式的額外引數。

    • eventName:型別是 String,事件名;
    • callback:型別是 Function,事件的回撥函式。

1、父元件與子元件的通訊

1)父元件

<template>
	<view>
		<test :title="title" @myEven="getNum" :name="name"></test>
	</view>
</template>

<script>
	import test from "../../components/test.vue"
	export default {
		data() {
			return {
				title : '標題',
				name: '張三'
			}
		},
		components: {
			test
		},
		methods: {
			getNum : function(num) {
				console.log('我已接收到 num: ', num);
			}
		}
	}
</script>

<style>
</style>

2)子元件

<template>
	<view>
		<text>我是test</text>
		<text :title="title">hello</text>
		<button @click="sentNum">按鈕來了</button>
		<text>父元件傳來的資料:{{name}}</text>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				title : '標題',
				num : 12
			};
		},
		props: ['name'],
		methods: {
			sentNum : function() {
				console.log('我是test,傳送num: ', this.num);
				this.$emit('myEven', this.num)
			}
		}
	}
</script>

<style>
</style>

2、兄弟元件之間的通訊

1)元件A

<template>
	<view>
		<button @click="addNum">我是A元件,我可以修改B元件的資料</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				
			};
		},
		methods: {
			addNum: function() {
				console.log('按啦');
				uni.$emit('updateNum', {});
			}
		}
	}
</script>

<style>
</style>

2)元件B

<template>
	<view>
		我是B元件,我的資料是:{{ num }}
	</view>
</template>

<script>
	export default {
		data() {
			return {
				num : 0
			};
		},
		created: function() {
			uni.$on('updateNum', ()=>{
				console.log('哈哈!');
				this.num ++;
			})
		}
	}
</script>

<style>
</style>


四、uni元件庫的使用(uni-ui擴充套件元件)

uni-ui 是 DCloud 提供的一個跨端 UI 庫,它是基礎元件的補充,我們可以通過 uni 官方 的外掛市場根據我們的需求引入相關的元件,它是一個非常不錯的選擇。
 
uni 官方 有很清楚的引入教程,在此也不作過多敘述,請大家根據自己的需要自行去官網尋找外掛。
 
擴充套件元件(uni-ui)https://uniapp.dcloud.io/component/README?id=uniui



部落格中若有不恰當的地方,請您一定要告訴我。前路崎嶇,望我們可以互相幫助,並肩前行!