gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:04:30 24 4
gpt4 key购买 nike

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://v2.vuejs.org/v2/guide/typescript.html#Class-Style-Vue-Componentshttps://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);
}
}

我收到以下错误:

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

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

Note:

  1. methods can be declared directly as class member methods.

  2. Computed properties can be declared as class property accessors.

  3. Initial data can be declared as class properties (babel-plugin-transform-class-properties is required if you use Babel).

  4. data, render and all Vue lifecycle hooks can be directly declared as class member methods as well, but you cannot invoke them on the instance itself. When declaring custom methods, you should avoid these reserved names.

  5. For all other options, pass them to the decorator function.

关于javascript - 如何在 Vue 类组件中定义过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52823903/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com