如何在Vue类组件中定义过滤器?

And*_*Mao 7 javascript typescript vue.js vuejs2

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)
  }
}
Run Code Online (Sandbox Code Playgroud)

以下是对它的一些引用:

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

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

{{ output | stringify }}
Run Code Online (Sandbox Code Playgroud)

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

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

  stringify(stuff: any) {
    return JSON.stringify(stuff, null, 2);
  }    
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

在此输入图像描述

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

tat*_*ato 7

在类组件中,关键是// All component options are allowed in heredocs中的comment():

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

这意味着在@Component部分中,您应该能够在其中添加filters包含过滤器函数的对象,如下所示

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

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

注意:

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

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

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

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

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