The Vue class component is a relatively new way of writing single-file components. It looks like this:
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)
}
}
Here are some references to it:
https://vuejs.org/v2/guide/typescript.html#Class-Style-Vue-Components https://github.com/vuejs/vue-class-component
However, none of those explain how to write filters in this syntax. If I try the following code in my template:
{{ output | stringify }}
And then try to write a filter as a class method, e.g.:
@Component
export default class HelloWorld extends Vue {
// ... other things
stringify(stuff: any) {
return JSON.stringify(stuff, null, 2);
}
}
I get the following error:
What's the right way to add a filter in this new syntax?
In Vue, we can define and implement the filter in two different ways which are explained below.
Going off number 2, because VueJS filters are meant for text transformations, they can only be used in two places: mustache interpolations (the curly braces in your template) and in v-bind expressions.
The quickest and easiest way to define a Vue component template is to add a template property to the component definition and assign a regular string containing your markup.
In a class component, the key is this comment (// All component options are allowed in here
) in the docs:
// The @Component decorator indicates the class is a Vue component
@Component({
// All component options are allowed in here
template: '<button @click="onClick">Click!</button>'
})
This means that in the @Component section you should be able to add a filters
object with your filter functions inside, like this
@Component({
// other options
filters: {
capitalize: function (value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
}
}
})
According to doc in https://github.com/vuejs/vue-class-component:
Note:
methods can be declared directly as class member methods.
Computed properties can be declared as class property accessors.
Initial data can be declared as class properties (babel-plugin-transform-class-properties is required if you use Babel).
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.
For all other options, pass them to the decorator function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With