zoukankan      html  css  js  c++  java
  • 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> {
        // ...
      }
    }
    
    声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。对于本博客如有任何问题,可发邮件与我沟通,我的QQ邮箱是:3074596466@qq.com
  • 相关阅读:
    深入理解java虚拟机笔记Chapter12
    深入理解java虚拟机笔记Chapter11
    深入理解java虚拟机笔记Chapter8
    深入理解java虚拟机笔记Chapter7
    深入理解java虚拟机笔记补充-JVM常见参数设置
    深入理解java虚拟机笔记Chapter4
    深入理解java虚拟机笔记Chapter3-内存分配策略
    Java从Txt文本进行数据提取
    C语言-格式输入输出中“%d,%o,%x,%e,%f,%s,%p”
    嵌入式学习书籍
  • 原文地址:https://www.cnblogs.com/CherishTheYouth/p/CherishTheYouth_20210725.html
Copyright © 2011-2022 走看看