Vue中的Class Component使用指南

更新日期: 2021-07-26阅读: 1.4k标签: 组件
本文由官方文档进行翻译而来,限于笔者英文能力和对技术理解能力有限,翻译或有不准确和出错之处,请多多包涵,可于评论中点出。
原文地址: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类型并在组件类型上继承它们。

以下是一个声明 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)
    })
  }
}

refsrefs` 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.fly63.com/article/detial/10582

Vuetify基于vue2.0,为移动而生的组件框架

Vuetify 支持SSR(服务端渲染),SPA(单页应用程序),PWA(渐进式Web应用程序)和标准HTML页面。 Vuetify是一个渐进式的框架,试图推动前端开发发展到一个新的水平。

Vue中插槽的作用_Vue组件插槽的使用以及调用组件内的方法

通过给组件传递参数, 可以让组件变得更加可扩展, 组件内使用props接收参数,slot的使用就像它的名字一样, 在组件内定义一块空间。在组件外, 我们可以往插槽里填入任何元素。slot-scope的作用就是把组件内的数据带出来

react 函数子组件(Function ad Child Component)

函数子组件(FaCC )与高阶组件做的事情很相似, 都是对原来的组件进行了加强,类似装饰者。FaCC,利用了react中children可以是任何元素,包括函数的特性,那么到底是如何进行增强呢?

Vue和React组件之间的传值方式

在现代的三大框架中,其中两个Vue和React框架,组件间传值方式有哪些?组件间的传值是灵活的,可以有多种途径,父子组件同样可以使用EventBus,Vuex或者Redux

vue.js自定义组件directives

自定义指令:以v开头,如:v-mybind。bind的作用是定义一个在绑定时执行一次的初始化动作,观察bind函数,它将指令绑定的DOM作为一个参数,在函数体中,直接操作DOM节点为input赋值。

vue中prop属性传值解析

prop的定义:在没有状态管理机制的时候,prop属性是组件之间主要的通信方式,prop属性其实是一个对象,在这个对象里可以定义一些数据,而这些数据可以通过父组件传递给子组件。 prop属性中可以定义属性的类型,也可以定义属性的初始值。

Web组件简介

Web组件由三个独立的技术组成:自定义元素。很简单,这些是完全有效的HTML元素,包含使用一组JavaScript API制作的自定义模板,行为和标记名称(例如,<one-dialog>)。

web组件调用其他web资源

web组件可以直接或间接的调用其他web资源。一个web组件通过内嵌返回客户端内容的另一个web资源的url来间接调用其他web资源。在执行时,一个web资源通过包含另一个资源的内容或者转发请求到另一个资源直接调用。

vue中如何实现的自定义按钮

在实际开发项目中,有时我们会用到自定义按钮;因为一个项目中,众多的页面,为了统一风格,我们会重复用到很多相同或相似的按钮,这时候,自定义按钮组件就派上了大用场,我们把定义好的按钮组件导出,在全局引用,就可以在其他组件随意使用啦,这样可以大幅度的提高我们的工作效率。

Vue子组件调用父组件的方法

Vue中子组件调用父组件的方法,这里有三种方法提供参考,第一种方法是直接在子组件中通过this.$parent.event来调用父组件的方法,第二种方法是在子组件里用$emit向父组件触发一个事件,父组件监听这个事件就行了。

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!