首页 > 解决方案 > 如何在 Vue 类组件中定义过滤器?

问题描述

Vue 类组件是一种相对较新的编写单文件组件的方式。它看起来像这样:

import Vue from 'vue'
import Component from 'vue-class-component'

// The @Component decorator indicates the class is a Vue component
@Component({
  // All component options are allowed in here
  template: '<button @click="onClick">Click!</button>'
})
export default class MyComponent extends Vue {
  // Initial data can be declared as instance properties
  message: string = 'Hello!'

  // Component methods can be declared as instance methods
  onClick (): void {
    window.alert(this.message)
  }
}

以下是对它的一些参考:

https://vuejs.org/v2/guide/typescript.html#Class-Style-Vue-Components https://github.com/vuejs/vue-class-component

但是,这些都没有解释如何用这种语法编写过滤器。如果我在模板中尝试以下代码:

{{ output | stringify }}

然后尝试将过滤器编写为类方法,例如:

@Component
export default class HelloWorld extends Vue {
  // ... other things

  stringify(stuff: any) {
    return JSON.stringify(stuff, null, 2);
  }    
}

我收到以下错误:

在此处输入图像描述

在这种新语法中添加过滤器的正确方法是什么?

标签: javascripttypescriptvue.jsvuejs2

解决方案


在类组件中,关键是// All component options are allowed in here文档中的此注释 ( ):

// The @Component decorator indicates the class is a Vue component
@Component({
  // All component options are allowed in here
  template: '<button @click="onClick">Click!</button>'
})

这意味着在 @Component 部分中,您应该能够添加一个filters带有过滤器功能的对象,如下所示

@Component({
  // other options
  filters: {
    capitalize: function (value) {
      if (!value) return ''
      value = value.toString()
      return value.charAt(0).toUpperCase() + value.slice(1)
    }
  }
})

根据https://github.com/vuejs/vue-class-component中的文档:

笔记:

  1. 方法可以直接声明为类成员方法。

  2. 计算属性可以声明为类属性访问器。

  3. 初始数据可以声明为类属性(如果使用 Babel,则需要 babel-plugin-transform-class-properties)。

  4. data、render 和所有 Vue 生命周期钩子也可以直接声明为类成员方法,但您不能在实例本身上调用它们。声明自定义方法时,应避免使用这些保留名称。

  5. 对于所有其他选项,将它们传递给装饰器函数。


推荐阅读