一、組件的基本概念
Vue 3是一個漸進式JavaScript框架,其中最核心的概念之一就是組件。所謂組件,就是一個封裝了自己的HTML、CSS和JS的獨立單元,可以通過組合不同的組件,搭建出更加複雜的頁面。組件可以傳遞參數、接收事件和響應狀態變化等操作,使得前端開發更加高效和模塊化。
二、組件的創建
Vue 3提供了兩種方式來創建組件。
1.基於對象的組件
const MyComponent = {
template: '<div>My Component</div>'
}
基於對象的組件是最簡單的形式,只需要定義一個包含template屬性的對象即可。在上述代碼中,我們創建了一個名為MyComponent的組件,模板中只包含了一個div元素和一段文本。這個組件可以在Vue實例中通過components屬性進行註冊,然後在模板中使用。
2.基於選項的組件
Vue.component('my-component', {
template: '<div>My Component</div>'
})
除了基於對象的組件外,Vue 3還提供了基於選項的組件創建方式。其中,Vue.component方法用來註冊全局組件,這種組件可以在應用的任何地方使用。組件名稱要使用kebab-case命名方式,同時,在模板中使用組件時,可以使用標籤進行引用。
三、組件的通信
組件之間的數據傳遞和通信是Vue 3中非常重要的一個概念,常用的方式包括:props、事件和$emit。
1.props
const ParentComponent = {
template: '<div><child-component :message="myMessage" /></div>',
data() {
return {
myMessage: 'Hello World'
}
},
components: {
ChildComponent
}
}
const ChildComponent = {
props: ['message'],
template: '<div>{{ message }}</div>'
}
上述代碼中,我們通過props屬性將父組件數據(myMessage)傳遞給了子組件。在子組件中,可以通過props屬性來接收傳遞過來的數據,然後在模板中進行渲染。
2.$emit
const ChildComponent = {
template: '<button @click="$emit(\'my-event\')">click me</button>'
}
const ParentComponent = {
template: '<div><child-component @my-event="handleClick" /></div>',
methods: {
handleClick() {
console.log('button clicked')
}
},
components: {
ChildComponent
}
}
在上述代碼中,我們在子組件中綁定了一個點擊事件,並通過$emit方法觸發了一個名為my-event的自定義事件。在父組件中,通過@符號綁定了這個自定義事件,並定義了一個handleClick方法進行響應。當子組件中的按鈕被點擊時,my-event自定義事件會觸發,從而觸發了handleClick方法。
四、組件的生命周期
組件的生命周期是Vue 3中非常關鍵的概念。生命周期鉤子函數可以幫助我們在不同階段控制組件行為,常用的生命周期鉤子函數包括:mounted、updated、beforeDestroy等。
1.mounted
const MyComponent = {
template: '<div>Hello World</div>',
mounted() {
console.log('mounted')
}
}
在上述代碼中,我們通過mounted生命周期鉤子函數定義了組件在掛載之後要執行的邏輯。在控制台中輸出了一個’mounted’的字符串。
2.updated
const MyComponent = {
template: '<div @click="updateMessage">{{ message }}</div>',
data() {
return {
message: 'Hello World'
}
},
methods: {
updateMessage() {
this.message = 'Hello Vue 3'
}
},
updated() {
console.log('updated')
}
}
在上述代碼中,我們定義了一個點擊事件updateMessage,在點擊元素後,會修改message的值。在數據更新之後,通過updated生命周期鉤子函數輸出了一個’updated’的字符串。
3.beforeDestroy
const MyComponent = {
template: '<div>Hello World</div>',
beforeDestroy() {
console.log('destroyed')
}
}
在上述代碼中,我們通過beforeDestroy生命周期鉤子函數定義了組件在銷毀之前要執行的邏輯。在控制台中輸出了一個’destroyed’的字符串。
五、組件的復用
Vue 3中,我們可以通過mixin和extends等方式來實現組件的復用。
1.mixin
const myMixin = {
methods: {
hello() {
console.log('Hello World')
}
}
}
const MyComponent = {
mixins: [myMixin],
template: '<div>{{ hello() }}</div>'
}
在上述代碼中,我們定義了一個名為myMixin的mixin對象,其中定義了一個hello方法。在MyComponent組件中,通過mixins屬性引入了myMixinMixin,然後在模板中使用hello方法進行渲染。這樣一來,我們就可以通過mixin來實現方法的共享和復用。
2.extends
const MyBaseComponent = {
template: '<div>Base Component</div>'
}
const MyComponent = {
extends: MyBaseComponent,
template: '<div>{{ message }}</div>',
data() {
return {
message: 'Extended Component'
}
}
}
在上述代碼中,我們定義了一個名為MyBaseComponent的基礎組件,在MyComponent組件中通過extends屬性來繼承基礎組件,並重新定義了模板內容和數據。這樣一來,我們就可以通過extends屬性來實現組件的復用和繼承。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/250478.html