Home >Web Front-end >Vue.js >typeof does not work in vue

typeof does not work in vue

下次还敢
下次还敢Original
2024-05-07 10:36:151284browse

Using typeof to check variable types in Vue may fail because Vue's reactive system proxies variables. Solutions include: 1. Use Vue.util.typeCheck; 2. Use Object.prototype.toString.call(myVariable); 3. Use Babel's transform-typeof-symbol plug-in.

typeof does not work in vue

typeof is invalid in Vue

In Vue.js, use the typeof operator Checking the type of a variable may not work because Vue's unique reactive system proxies variables.

Cause:

When a variable is reactively proxied, it is replaced by a wrapper object. This wrapper object hijacks access to the variable, allowing it to automatically trigger updates when the value changes.

Solution:

In order to correctly check the type of a variable in Vue, you can use one of the following methods:

  • Using Vue.util.typeCheck:
<code class="js">import { typeCheck } from 'vue/types/util'
typeCheck(myVariable) === 'Object' // true</code>
  • Using Object.prototype.toString.call(myVariable):
<code class="js">Object.prototype.toString.call(myVariable) === '[object Object]' // true</code>
  • Use Babel’s transform-typeof-symbol plugin:

This plugin will Compile the typeof operator into a more reliable alternative. Please refer to the Babel documentation for specific usage.

Note:

  • ##Vue.util.typeCheck can only check basic types (such as Object, Array and String).
  • Object.prototype.toString.call(myVariable) Can check a wider range of types, including Vue-specific types.
  • Babel’s
  • transform-typeof-symbol plugin needs to be enabled in the Babel configuration.

The above is the detailed content of typeof does not work in vue. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What does ref mean in vueNext article:What does ref mean in vue