Vue中的Class Component使用指南


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 = '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類型並在組件類型上繼承它們。

以下是一個聲明 HelloWorld 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> {
    // ...
  }
}

以上代碼產生了一個類型錯誤,該錯誤指出,屬性 fetchPostwatch 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> {
    // ...
  }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM