LoginSignup
7
2

More than 3 years have passed since last update.

【Vue】filtersでthisが使えない

Last updated at Posted at 2020-06-21

Vueのfiltersthisが使えなかった話

Vue.jsのfiltersで↓のようなコードを書いて実行しようとしたらエラーがでた。

最初はMixinとして使っていたためMixinではfiltersは使えないのかと思い、普通にコンポーネント内のfiltersプロパティ内で使っても同じエラーがでたので調べることにした。

ちなみにfiltersというのはVue固有のプロパティの一つで、ここに定義した関数をムスタッシュ構文内で例えば{{ <data> | oneFilter }}のようにして使うと<data>oneFilterで加工することができる。


<template>
  <div id="app">
    <p>{{ '選択してください' |  processChoice }}</p>
  </div>
</template>

<script>
new Vue({
  el: '#app',

  computed: {
    getName (obj) {
        if (obj) {
            return obj.name
        }
    }
  },

  filters: {
    processChoice(value) {
      if (this.getName) {
        return this.getName
      }
      return value
    }
  }
})
</script>
エラーメッセージ
Cannot read property 'getName' of undefined...

結論

先に結論を書いてしまうと、「Vueのfiltersプロパティではthis(Vueインスタンス)にはアクセスできないようなので、computedmethodsを使いましょう」ということらしいです。

filtersで定義した関数内からthisにアクセスできないので、undefinedエラーが出ているということですね。

調べたこととか

  1. this undefined in filters #5998
  2. VueJSのfilters内でmethodが使えない

1番目のリンクのissueに対する回答で、Evan You(Vue.jsの作者)がfiltersでは敢えてVueインスタンスにアクセスできないようににしていると言っています。filtersでは純粋なJSの関数を使うことしか現状できないようです。どうしてもthisを使う必要がある時は結論に書いたようにfiltersではなく、computedmethodsに処理をまとめて書いてそれを使いましょう。(compotedmethodsもムスタッシュ構文に埋め込むことが可能です。)

何人かの開発者がfilters内でthisを使えるようにして欲しいと書いていますが、
作者が↓のように言っているのでVue3系でも同じ仕様になるような気がします。

I'm absolutely convinced that filters must have a way access the context. The question's what core team is going to do about it?

Sorry but my opinion has not changed: filters should not, and will not have access to context. If you need context, use a method.

7
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2