Vue中的Class Component使用指南
本文由官方檔案進行翻譯而來,限于筆者英文能力和對技術理解能力有限,翻譯或有不準確和出錯之處,請多多包涵,可于評論中點出,
原文地址:Vue Class Component
一般性指引
使用@Component注解,將類轉化為 Vue 的組件,以下是一個示例
import Vue from 'vue'
import Component from 'vue-class-component'
// HelloWorld class will be a Vue component
@Component
export default class HelloWorld extends Vue {}
Data屬性
data屬性初始化可以被宣告為類的屬性,
<template>
<div>{{ message }}</div>
</template>
<script>
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export default class HelloWorld extends Vue {
// Declared as component data
message = 'Hello World!'
}
</script>
上面的組件,將message渲染到div元素種,作為組件的 data
需要注意的是,如果未定義初始值,則類屬性將不會是相應式的,這意味著不會檢測到屬性的更改:
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export default class HelloWorld extends Vue {
// `message` will not be reactive value
message = undefined
}
為了避免這種情況,可以使用 null 對值進行初始化,或者使用 data()構造鉤子函式,如下:
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export default class HelloWorld extends Vue {
// `message` will be reactive with `null` value
message = null
// See Hooks section for details about `data` hook inside class.
data() {
return {
// `hello` will be reactive as it is declared via `data` hook.
hello: undefined
}
}
}
Methods屬性
組件方法可以直接宣告為類的原型方法:
<template>
<button v-on:click="hello">Click</button>
</template>
<script>
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export default class HelloWorld extends Vue {
// Declared as component method
hello() {
console.log('Hello World!')
}
}
</script>
Computed Properties(計算屬性)
計算屬性可以宣告為類屬性getter/setter:
<template>
<input v-model="name">
</template>
<script>
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export default class HelloWorld extends Vue {
firstName = 'John'
lastName = 'Doe'
// Declared as computed property getter
get name() {
return this.firstName + ' ' + this.lastName
}
// Declared as computed property setter
set name(value) {
const splitted = value.split(' ')
this.firstName = splitted[0]
this.lastName = splitted[1] || ''
}
}
</script>
Hooks
data()方法,render()方法和所有的宣告周期鉤子函式,也都可以直接宣告為類的原型方法,但是,不能在實體本身上呼叫它們,
當宣告自定義方法時,注意命名不要與這些hooks方法名相沖突,
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export default class HelloWorld extends Vue {
// Declare mounted lifecycle hook
mounted() {
console.log('mounted')
}
// Declare render function
render() {
return <div>Hello World!</div>
}
}
Other Options
對于其他所有選項,則需要將其寫到注解 @Component中,
<template>
<OtherComponent />
</template>
<script>
import Vue from 'vue'
import Component from 'vue-class-component'
import OtherComponent from './OtherComponent.vue'
@Component({
// Specify `components` option.
// See Vue.js docs for all available options:
// https://vuejs.org/v2/api/#Options-Data
components: {
OtherComponent
}
})
export default class HelloWorld extends Vue {
firstName = 'John'
lastName = 'Doe'
// Declared as computed property getter
get name() {
return this.firstName + ' ' + this.lastName
}
// Declared as computed property setter
set name(value) {
const splitted = value.split(' ')
this.firstName = splitted[0]
this.lastName = splitted[1] || ''
}
// Declare mounted lifecycle hook
mounted() {
console.log('mounted')
}
// Declare render function
render() {
return <div>Hello World!</div>
}
}
</script>
如果您使用一些Vue插件(如Vue Router),你可能希望類組件決議它們提供的鉤子,在這種情況下,可以只用Component.registerHooks來注冊這些額外的鉤子:
- class-component-hooks.js 是一個單獨的檔案,需要新建,然后倒入到
main.ts中,或者直接在main.ts中進行注冊,
// class-component-hooks.js
import Component from 'vue-class-component'
// Register the router hooks with their names
Component.registerHooks([
'beforeRouteEnter',
'beforeRouteLeave',
'beforeRouteUpdate'
])
- main.ts
// main.js
// Make sure to register before importing any components
import './class-component-hooks'
import Vue from 'vue'
import App from './App'
new Vue({
el: '#app',
render: h => h(App)
})
在注冊完這些鉤子后,在類組件中,可以把它們當成類的原型方法來使用:
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export default class HelloWorld extends Vue {
// The class component now treats beforeRouteEnter,
// beforeRouteUpdate and beforeRouteLeave as Vue Router hooks
beforeRouteEnter(to, from, next) {
console.log('beforeRouteEnter')
next()
}
beforeRouteUpdate(to, from, next) {
console.log('beforeRouteUpdate')
next()
}
beforeRouteLeave(to, from, next) {
console.log('beforeRouteLeave')
next()
}
}
建議將注冊的程序,寫到一個單獨的檔案中,因為注冊的程序必須在任何組件定義和匯入之前進行,
通過將鉤子注冊的import陳述句放在main.ts的頂部,可以確保執行順序:
// main.js
// Make sure to register before importing any components
import './class-component-hooks'
import Vue from 'vue'
import App from './App'
new Vue({
el: '#app',
render: h => h(App)
})
Custom Decorators(自定義裝飾器)
你可以通過自定義裝飾器來擴展此庫的功能,
Vue-class-component 提供了 createDecorator幫助器 來創建自定義裝飾器,
createDecorator的第一個引數為一個回呼函式,這個回呼函式接收如下引數:
- options:一個Vue組件Options 物件,此物件的改變將會直接影響到相應的組件,
- key:裝飾器提供的屬性或方法的鍵值,
- parameterIndex:引數索引,如果自定義裝飾器被用來裝飾引數,則parameterIndex 用來表示引數的索引,
以下是一個創建一個日志裝飾器的示例程式,該裝飾器的作用是:
當被裝飾的方法被呼叫時,列印該方法的方法名和傳遞進來的引數,
// decorators.js
import { createDecorator } from 'vue-class-component'
// Declare Log decorator.
export const Log = createDecorator((options, key) => {
// Keep the original method for later.
const originalMethod = options.methods[key]
// Wrap the method with the logging logic.
options.methods[key] = function wrapperMethod(...args) {
// Print a log.
console.log(`Invoked: ${key}(`, ...args, ')')
// Invoke the original method.
originalMethod.apply(this, args)
}
})
將其作為方法裝飾器使用:
import Vue from 'vue'
import Component from 'vue-class-component'
import { Log } from './decorators'
@Component
class MyComp extends Vue {
// It prints a log when `hello` method is invoked.
@Log
hello(value) {
// ...
}
}
當hello()執行時,引數為 42 時,其列印結果為:
Invoked: hello( 42 )
Extends
可以通過繼承的方式,擴展一個已有的類,假設你有一個如下的超類組件:
// super.js
import Vue from 'vue'
import Component from 'vue-class-component'
// Define a super class component
@Component
export default class Super extends Vue {
superValue = 'https://www.cnblogs.com/CherishTheYouth/archive/2021/07/25/Hello'
}
你可以通過如下的類繼承語法來擴展它:
import Super from './super'
import Component from 'vue-class-component'
// Extending the Super class component
@Component
export default class HelloWorld extends Super {
created() {
console.log(this.superValue) // -> Hello
}
}
需要注意的是,每個超型別都必須是類組件,換句話說,它需要繼承Vue建構式作為基類,并且,必須要有@Component裝飾器進行裝飾,
Mixins
vue-class-component 提供mixins幫助器,使其支持以類的風格使用 mixins.
通過使用mixins幫助器,TypeScript可以推斷mixin型別并在組件型別上繼承它們,
以下是一個宣告 Hello 和 World Mixins的示例:
// mixins.js
import Vue from 'vue'
import Component from 'vue-class-component'
// You can declare mixins as the same style as components.
@Component
export class Hello extends Vue {
hello = 'Hello'
}
@Component
export class World extends Vue {
world = 'World'
}
在一個類組件中使用它們:
import Component, { mixins } from 'vue-class-component'
import { Hello, World } from './mixins'
// Use `mixins` helper function instead of `Vue`.
// `mixins` can receive any number of arguments.
@Component
export class HelloWorld extends mixins(Hello, World) {
created () {
console.log(this.hello + ' ' + this.world + '!') // -> Hello World!
}
}
和Extends中的超類一樣,所有的mixins都必須定義為類式組件,
Caveats of Class Component(類組件的注意事項)
屬性初始化時的 this 值的問題
如果你用箭頭函式的形式,定義一個類屬性(方法),當你在箭頭函式中呼叫 this 時,這將不起作用,這是因為,在初始化類屬性時,this只是Vue實體的代理物件,
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export default class MyComp extends Vue {
foo = 123
// DO NOT do this
bar = () => {
// Does not update the expected property.
// `this` value is not a Vue instance in fact.
this.foo = 456
}
}
在這種情況下,你可以簡單的定義一個方法,而不是一個類屬性,因為Vue將自動系結實體:
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export default class MyComp extends Vue {
foo = 123
// DO this
bar() {
// Correctly update the expected property.
this.foo = 456
}
}
應當總是使用宣告周期鉤子而非使用建構式
由于原始的建構式已經被使用來收集初始組件的 data資料,因此,建議不要自行使用建構式,
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export default class Posts extends Vue {
posts = []
// DO NOT do this
constructor() {
fetch('/posts.json')
.then(res => res.json())
.then(posts => {
this.posts = posts
})
}
}
上面的代碼打算在組件初始化時獲取post串列,但是由于Vue類組件的作業方式,fetch程序將被呼叫兩次,
建議使用組件宣告周期函式,如 creatd() 而非建構式(constructor),
TypeScript使用指引
屬性定義(Props Definition)
Vue-class-component 沒有提供屬性定義的專用 Api,但是,你可以使用 canonical Vue.extend API 來完成:
<template>
<div>{{ message }}</div>
</template>
<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
// Define the props by using Vue's canonical way.
const GreetingProps = Vue.extend({
props: {
name: String
}
})
// Use defined props by extending GreetingProps.
@Component
export default class Greeting extends GreetingProps {
get message(): string {
// this.name will be typed
return 'Hello, ' + this.name
}
}
</script>
由于Vue.extend會推斷已定義的屬性型別,因此可以通過繼承它們在類組件中使用它們,
如果你同時還需要擴展 超類組件 或者 mixins 之類的,可以使用 mixins 幫助器 將定義的屬性和 超類組價,mixins 等結合起來:
<template>
<div>{{ message }}</div>
</template>
<script lang="ts">
import Vue from 'vue'
import Component, { mixins } from 'vue-class-component'
import Super from './super'
// Define the props by using Vue's canonical way.
const GreetingProps = Vue.extend({
props: {
name: String
}
})
// Use `mixins` helper to combine defined props and a mixin.
@Component
export default class Greeting extends mixins(GreetingProps, Super) {
get message(): string {
// this.name will be typed
return 'Hello, ' + this.name
}
}
</script>
屬性型別宣告(Property Type Declaration)
有時候,你不得不在類組件之外定義屬性和方法,例如,Vue的官方狀態管理庫 Vuex 提供了 MapGetter 和 mapActions幫助器,用于將 store 映射到組件屬性和方法上,這些幫助器,需要在 組件選項物件中使用,即使在這種情況下,你也可以將組件選項傳遞給@component decorator的引數,
但是,當屬性和方法在運行時作業時,它不會在型別級別自動宣告它們,
你需要在組件中手動宣告它們的型別:
import Vue from 'vue'
import Component from 'vue-class-component'
import { mapGetters, mapActions } from 'vuex'
// Interface of post
import { Post } from './post'
@Component({
computed: mapGetters([
'posts'
]),
methods: mapActions([
'fetchPosts'
])
})
export default class Posts extends Vue {
// Declare mapped getters and actions on type level.
// You may need to add `!` after the property name
// to avoid compilation error (definite assignment assertion).
// Type the mapped posts getter.
posts!: Post[]
// Type the mapped fetchPosts action.
fetchPosts!: () => Promise<void>
mounted() {
// Use the mapped getter and action.
this.fetchPosts().then(() => {
console.log(this.posts)
})
}
}
\(refs 型別擴展(`\)refs` Type Extension)
組件的$refs型別被宣告為處理所有可能的ref型別的最廣泛的型別,雖然理論上是正確的,但在大多數情況下,每個ref在實踐中只有一個特定的元素或組件,
可以通過重寫類組件中的$refs type來指定特定的ref型別:
<template>
<input ref="input">
</template>
<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export default class InputFocus extends Vue {
// annotate refs type.
// The symbol `!` (definite assignment assertion)
// is needed to get rid of compilation error.
$refs!: {
input: HTMLInputElement
}
mounted() {
// Use `input` ref without type cast.
this.$refs.input.focus()
}
}
</script>
您可以訪問input型別,而不必將型別轉換為$refs,在上面的示例中,input型別是在類組件上指定的,
請注意,它應該是型別注釋(使用冒號:)而不是賦值(=),
鉤子自動完成(Hooks Auto-complete)
Vue-class-component 提供了內置的鉤子型別,在 TypeScript 中,它可以自動完成類組件宣告中 data()、render(),及其他生命周期函式的型別推導,要啟用它,您需要匯入vue-class-component/hooks 中的鉤子型別,
// main.ts
import 'vue-class-component/hooks' // import hooks type to enable auto-complete
import Vue from 'vue'
import App from './App.vue'
new Vue({
render: h => h(App)
}).$mount('#app')
如果你想在自定義鉤子函式中使用它,你可以手動進行添加,
import Vue from 'vue'
import { Route, RawLocation } from 'vue-router'
declare module 'vue/types/vue' {
// Augment component instance type
interface Vue {
beforeRouteEnter?(
to: Route,
from: Route,
next: (to?: RawLocation | false | ((vm: Vue) => void)) => void
): void
beforeRouteLeave?(
to: Route,
from: Route,
next: (to?: RawLocation | false | ((vm: Vue) => void)) => void
): void
beforeRouteUpdate?(
to: Route,
from: Route,
next: (to?: RawLocation | false | ((vm: Vue) => void)) => void
): void
}
}
在Decorator中注釋組件型別(Annotate Component Type in Decorator)
在某些情況下,你希望在@component decorator引數中的函式上使用組件型別,例如,需要在 watch handler 中訪問組件方法:
@Component({
watch: {
postId(id: string) {
// To fetch post data when the id is changed.
this.fetchPost(id) // -> Property 'fetchPost' does not exist on type 'Vue'.
}
}
})
class Post extends Vue {
postId: string
fetchPost(postId: string): Promise<void> {
// ...
}
}
以上代碼產生了一個型別錯誤,該錯誤指出,屬性 fetchPost 在watch handler 中不存在,之所以會發生這種情況,是因為@Component decorator引數中的this型別是Vue基型別,
要使用自己的組件型別(在本例中是Post),可以通過decorator的型別引數對其進行注釋,
// Annotate the decorator with the component type 'Post' so that `this` type in
// the decorator argument becomes 'Post'.
@Component<Post>({
watch: {
postId(id: string) {
this.fetchPost(id) // -> No errors
}
}
})
class Post extends Vue {
postId: string
fetchPost(postId: string): Promise<void> {
// ...
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/289992.html
標籤:其他
