Vue: instanceof in expressions does not work

Created on 24 Feb 2018  路  6Comments  路  Source: vuejs/vue

Version

2.5.13

Reproduction link

https://jsfiddle.net/50wL7mdz/127177/

Steps to reproduce

  1. create a class
  2. set data to use an instance of that class
  3. create expression in for example a "v-if" using instanceof

Note that the expression does not return true (the span is not rendered in example) while it is expected

What is expected?

expression evaluates to true

What is actually happening?

expression does not return true resulting in not displayed span


workaround is to create expression in the form of "instance.contructor.name === 'A'". But this is not typesafe, and it "stringly-typed" instead thus not toolable.

Most helpful comment

An other approach is to use a method.

First, import your class definition :
import { MyClass } from './myClass.js'

then, implements a method to test it :

methods: {
  isMyClass (item) {
      return item instanceof MyClass
  }
}

and then use it in your v-if :
v-if="isMyClass(item)"

All 6 comments

You need to let Vue know about A to use it the templates. You can either add it to data or do Vue.prototype.A = A

Thanks! This fixed the issue. It's still suboptimal, as I have to make a huge list of types I'm using - I can solve this by automating it. Is it possible for me to write a "proper" fix for Vue to make this happen? Or is there a limitation this workaround fixes?

Second, I have searched the docs for instanceof, but did not find anything related. Did I miss something, or can I fix this by explaining this somewhere?

No, there no fix for this. You need to explicitly add classes the same way you add any data.
Using instances in data is usually not a good idea as most of them are not serializable, making it hard to use in SSR applications. That's why you didn't found it in the docs 馃槈

@generateui What did you do to fix the issue? Adding the class to Vue.prototype didn't work for me.

In my index.js, I import { MyClass } from './myClass.js';. Then, I do Vue.prototype.MyClass = MyClass. Then it works. See also: my index.js file.

An other approach is to use a method.

First, import your class definition :
import { MyClass } from './myClass.js'

then, implements a method to test it :

methods: {
  isMyClass (item) {
      return item instanceof MyClass
  }
}

and then use it in your v-if :
v-if="isMyClass(item)"

Was this page helpful?
0 / 5 - 0 ratings

Related issues

eu81273 picture eu81273  路  40Comments

rpkilby picture rpkilby  路  50Comments

karevn picture karevn  路  36Comments

asiFarran picture asiFarran  路  34Comments

cherry-geqi picture cherry-geqi  路  35Comments