I'm trying to use a global variable in my vue template. I'm trying to use it without setting it in the data fields, because they're actually some global constants.
<template v-if="item.WheelDrive === WHEEL_DRIVE.ALLROAD">
this will give me the "Property or method is not defined on the instance but referenced during render" error.
Is it possible to direct vue not to try and bind WHEEL_DRIVE here?
In Vue, templating is the main way we create reusable components. We can use templates to take data, and turn it into real elements on a screen that users can see.
Global Variables are the variables that can be accessed from anywhere in the program. These are the variables that are declared in the main body of the source code and outside all the functions. These variables are available to every function to access. Var keyword is used to declare variables globally.
You can use computed
or even create a custom mixin
to get a global value:
<div id="app">
<p>
Example 1: {{myGlobalVariable}}
</p>
<p>
Example 2: {{getGlobal('globalVariable')}}
</p>
</div>
<script>
window.globalVariable = 'I am a global thing';
new Vue({
el: "#app",
data: {
},
computed: {
myGlobalVariable: function () {
return globalVariable;
},
},
methods: {
// this could be a mixin (see vue docs how to create a global mixin)
getGlobal(propertyName) {
if (propertyName) {
//return this.$el.ownerDocument.defaultView[propertyName];
//return eval(propertyName); // !!! be careful with that, it opens a hole into security
return window[propertyName];
} else {
return null;
}
}
}
})
</script>
Depending on where you are you can also use:
this[propertyName];
self[propertyName];
window[propertyName];
top[propertyName];
globalThis[propertyName];
eval(propertyName); // !!! be careful with that, it opens a hole into security
If you are looking for a global function:
window[functionName](arg1, arg2);
See the following example https://jsfiddle.net/FairKing/u7y034pf/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With