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

然而,这些都没有解释如何用这种语法编写过滤器.如果我在模板中try 以下代码:

{{ output | stringify }}

然后try 将筛选器作为类方法编写,例如:

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

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

我得到以下错误:

enter image description here

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

推荐答案

在类组件中,关键是文档中的注释(// 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)
    }
  }
})

根据doc在https://github.com/vuejs/vue-class-component中的说法:

注:

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

  2. 计算(computed)属性可以声明为类属性访问器.

  3. 初始数据可以声明为类属性(如果使用babel,则需要babel插件转换类属性).

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

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

Vue.js相关问答推荐

在预渲染模式下部署 nuxt 3 时出错

在移动版本中使用标准的 v-data-table

Vue 3 如何通过多个组件传递插槽

为什么将 name 与 router-link 一起使用比仅使用 to 与 path 更好?

VueJS:在组件之间使用全局对象的最佳实践?

vuejs vue-cli 如何使用 console.log 而不会出现任何错误

Vue CLI - 编译后将配置文件保留为外部

如何在 Vue.js 中获取完整的当前日期和时间,而无需编写大量 JavaScript 行

在 jest document.querySelector 中测试 vue 组件期间始终返回 null

Vuetify 在数据表中插入操作按钮并获取行数据

正确实现 Vue.js + DataTables

Vue @click 不适用于存在 href 的anchor锚标记

Vue test-utils 如何测试 router.push()

store 的 Vuex Classic 模式已弃用,将在 Nuxt 3 中删除

如何使用 VueJS / Typescript 导入 JSON 文件?

v-if inside v-for - 在两列中显示项目列表

Vuetify v-btn 路由活动类问题

如何从浏览器的源中删除 webpack://

带有 Google Auth Signin 的 Vuejs 全局函数

在 Vue 中使用事件修饰符 .prevent 提交表单而不进行重定向