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 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:
Vue.util.typeCheck
: <code class="js">import { typeCheck } from 'vue/types/util' typeCheck(myVariable) === 'Object' // true</code>
Object.prototype.toString.call(myVariable)
: <code class="js">Object.prototype.toString.call(myVariable) === '[object Object]' // true</code>
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:
can only check basic types (such as
Object,
Array and
String).
Can check a wider range of types, including Vue-specific types.
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!