[英]How do I define a filter in a Vue class component?
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-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 生命周期鈎子也可以直接聲明為類成員方法,但您不能在實例本身上調用它們。 聲明自定義方法時,應避免使用這些保留名稱。
對於所有其他選項,將它們傳遞給裝飾器函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.