天天看點

Vue中的Class Component使用指南

Vue中的Class Component使用指南

作者 | CherishTheYouth

一般性指引

使用@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類型并在元件類型上繼承它們。

以下是一個聲明 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類型擴充(‘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> {
    // ...
  }
}      

感謝閱讀,本文到此結束。

學習更多技能

請點選下方公衆号

繼續閱讀