Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use global variable in vue template

Tags:

vue.js

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?

like image 688
user2154171 Avatar asked Jan 05 '19 18:01

user2154171


People also ask

What does template tag do in Vue?

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.

How do you define a global variable in Javascript?

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.


1 Answers

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/

like image 61
ADM-IT Avatar answered Oct 10 '22 20:10

ADM-IT