簡體   English   中英

如何在 Vue 類組件中定義過濾器?

[英]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中的文檔:

筆記:

  1. 方法可以直接聲明為類成員方法。

  2. 計算屬性可以聲明為類屬性訪問器。

  3. 初始數據可以聲明為類屬性(如果使用 Babel,則需要 babel-plugin-transform-class-properties)。

  4. data、render 和所有 Vue 生命周期鈎子也可以直接聲明為類成員方法,但您不能在實例本身上調用它們。 聲明自定義方法時,應避免使用這些保留名稱。

  5. 對於所有其他選項,將它們傳遞給裝飾器函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM