javascript - 如何在 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);
}
}
我收到以下错误:
在这种新语法中添加过滤器的正确方法是什么?
解决方案
在类组件中,关键是// 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中的文档:
笔记:
方法可以直接声明为类成员方法。
计算属性可以声明为类属性访问器。
初始数据可以声明为类属性(如果使用 Babel,则需要 babel-plugin-transform-class-properties)。
data、render 和所有 Vue 生命周期钩子也可以直接声明为类成员方法,但您不能在实例本身上调用它们。声明自定义方法时,应避免使用这些保留名称。
对于所有其他选项,将它们传递给装饰器函数。
推荐阅读
- javascript - 从服务器删除加载的文件
- javascript - 如何更改数组 BehaviorSubject 中对象的值?
- javascript - 隐藏选项卡时从 setInterval 启动操作
- sql - 使用最大/聚合函数
- java - 如何在 Spigot 1.16.5 中创建自定义项目?
- ios - 无法触发长按手势 [UiView]
- regex - 正则表达式在 Alteryx 中不起作用
- c# - 当数组绑定到 UWP 应用程序中的可见性属性时,如何侦听数组中的更改
- reactjs - 如何让 React 类组件在登录后保持其状态,并根据组件中当前可用的状态更改可用路由?
- django - Django Rest 框架和 React Linkedin 社交身份验证 OAuth2Error