从零开始封装 vue 组件
對于學習 Vue 的同學來說,封裝 vue 組件是實現(xiàn)代碼復用的重要一環(huán)。在 Vue 官網中非常詳細地介紹了 vue 組件的相關知識,我這里簡單摘取使用最頻繁的幾個知識點,帶大家快速入門 vue 組件的使用。
快速入門
我們假設在頁面上有很多地方都要用到一個計數(shù)器,與其在每個地方都實現(xiàn)計數(shù)器功能,不如封裝一個計數(shù)器組件,隨后在需要的地方引用。于是,我們定義了如下代碼所示的計數(shù)器組件:
<script>
export default {
data() {
return {
count: 0
}
}
}
</script>
<template>
<button @click="count++">
You clicked me {{ count }} times.
</button>
</template>
隨后,我們在需要的地方引用計數(shù)器組件,如下代碼所示。
<script>
import ButtonCounter from './ButtonCounter.vue'
export default {
components: {
ButtonCounter
}
}
</script>
<template>
<h1>Here are many child components!</h1>
<ButtonCounter />
<ButtonCounter />
<ButtonCounter />
</template>
運行效果如下圖所示。
本例運行內容及效果可在這里查看:簡單的計數(shù)器組件。
到這里,我們就完成了一個簡單地 vue 組件的封裝。
傳遞參數(shù)
在封裝組件的時候,我們可能需要向組件中傳遞參數(shù),從而實現(xiàn)不同的業(yè)務邏輯。例如:我們需要封裝一個博文的組件,我們需要向組件中傳遞標題和內容,這時候我們就需要用到傳遞參數(shù) —— props。對于博文組件,我們對于組件的封裝如下代碼所示。
<script>
export default {
props: ['title']
}
</script>
<template>
<h4>{{ title }}</h4>
</template>
接著,我們在頁面上引用博文組件,如下代碼所示。
<script>
import BlogPost from './BlogPost.vue'
export default {
components: {
BlogPost
},
data() {
return {
posts: [
{ id: 1, title: 'My journey with Vue' },
{ id: 2, title: 'Blogging with Vue' },
{ id: 3, title: 'Why Vue is so fun' }
]
}
}
}
</script>
<template>
<BlogPost
v-for="post in posts"
:key="post.id"
:title="post.title"
></BlogPost>
</template>
運行效果如下圖所示:
本例運行內容及效果可在這里查看:傳遞參數(shù)的博文組件
監(jiān)聽事件
有時候,我們不僅希望能往組件中傳遞參數(shù),也希望父組件能感知子組件的變化。例如:我們希望可以通過子組件來設置父組件的文字大小,從而動態(tài)改變文章的文字大小。這時候,我們可以在子組件中使用 $emit() 來觸發(fā)事件,在父組件使用 @enlarge-text 來監(jiān)聽事件,如下代碼所示。
// BlogPost.vue
<script>
export default {
props: ['title'],
emits: ['enlarge-text']
}
</script>
<template>
<div class="blog-post">
<h4>{{ title }}</h4>
<button @click="$emit('enlarge-text')">Enlarge text</button>
</div>
</template>
如上代碼所示,我們在 export default 的 emits 屬性中注明了該組件會拋出 enlarge-text 事件。隨后,我們在按鈕點擊時,使用 $emit('enlarge-text') 拋出了 enlarge-text 事件。
<script>
import BlogPost from './BlogPost.vue'
export default {
components: {
BlogPost
},
data() {
return {
posts: [
{ id: 1, title: 'My journey with Vue' },
{ id: 2, title: 'Blogging with Vue' },
{ id: 3, title: 'Why Vue is so fun' }
],
postFontSize: 1
}
}
}
</script>
<template>
<div :style="{ fontSize: postFontSize + 'em' }">
<BlogPost
v-for="post in posts"
:key="post.id"
:title="post.title"
@enlarge-text="postFontSize += 0.1"
></BlogPost>
</div>
</template>
在上述代碼中,我們在父組件中使用 @enlarge-text 監(jiān)聽 enlarge-text 事件。當監(jiān)聽到該事件后,我們將 postFontSize 的值加 0.1,從而實現(xiàn)動態(tài)改變文字大小的目的。
總結
關于 vue 組件的使用,props 和事件傳遞可以說是使用最頻繁的兩個功能。對于更復雜的組件來說,肯定還有更多更復雜的語法和功能。但對于初學者來說,學得夠用就行,后續(xù)需要時再慢慢學習。關于 vue 組件更多內容,可以參考 vue 官網相關章節(jié):組件基礎 | Vue.js
參考資料
- 組件基礎 | Vue.js
- 從零開始封裝組件(一):功能按鈕欄 - 掘金
- 淺嘗 | 從 0 到 1 Vue 組件庫封裝 - 掘金
- 年輕人如何從0到1封裝發(fā)布一個vue組件 - 掘金
總結
以上是生活随笔為你收集整理的从零开始封装 vue 组件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 家里wifi不好用怎么办?民科帝教你判断
- 下一篇: html5倒计时秒杀怎么做,vue 设