【问题标题】:How do I define a filter in a Vue class component?如何在 Vue 类组件中定义过滤器?
【发布时间】:2019-03-20 07:18:33
【问题描述】:

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);
  }    
}

我收到以下错误:

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

【问题讨论】:

标签: javascript typescript vue.js vuejs2


【解决方案1】:

在类组件中,关键是文档中的这条注释 (// 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. 数据、渲染和所有 Vue 生命周期钩子也可以直接声明为类成员方法,但不能在实例本身上调用它们。声明自定义方法时,应避免使用这些保留名称。

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

【讨论】:

  • 我也尝试使用computed 来执行此操作,但类型检查器不喜欢这样:当我尝试访问@987654330 中的this.foo 时,它说Property 'foo 在类型Vue` 上不存在@。有什么提示吗?
  • @AndrewMao 请阅读github.com/vuejs/vue-class-component,下面的“注意:” 1. 方法可以直接声明为类成员方法。 2. 计算属性可以声明为类属性访问器。 3. 初始数据可以声明为类属性, 4. data、render 和所有 Vue 生命周期钩子也可以直接声明为类成员方法,但不能在实例本身上调用它们。声明自定义方法时,应避免使用这些保留名称。 5. 对于所有其他选项,将它们传递给装饰器函数。
猜你喜欢
  • 2017-11-22
  • 2018-08-24
  • 2018-11-28
  • 1970-01-01
  • 1970-01-01
  • 2018-03-17
  • 2017-06-06
  • 2020-08-07
相关资源
最近更新 更多