D
D
Dilik Pulatov2017-07-24 10:48:34
Vue.js
Dilik Pulatov, 2017-07-24 10:48:34

How to make global variables and method in VueJs2?

Hello!
In Vu how to make global variables and method or how to use own methods or variables in any component?
for example i have in main.js

new Vue({
  el: '#app',
  data:{
    globalVar: 'my variable',
  },
  methods:{
    myGlobalMethods(){
      // code
    }
  }
});

how can i use globalVar and myGlobalMethods anywhere?
and I also have the same variables and methods in App.vue, how can I use them in any component so as not to write again? (can I also change the values ​​of variables in another component?)

Answer the question

In order to leave comments, you need to log in

6 answer(s)
A
Artem0071, 2017-07-24
@Artem0071

vuex

E
Evgeny Kulakov, 2017-07-24
@kulakoff Vue.js

You can generally organize it like this:
Storage file:

// store.js
export default {
    a: 'foo',
    b: 'bar'
}

Implementing storage in Vue:
import Vue from 'vue'
import Store from './store'

new Vue({
  el: '#app',
  data: Store,
  render: h => h(App)
})

Appeal in any component:
<template>
    <div>{{$root.a}}</div>
</template>

<script>
import Store from './store'
export default {
  name: 'app',
  methods: {
    test () {
      this.$root.a = 'something value' 
    }
  }
}

V
Vladimir Zhosan, 2017-07-24
@iaskivsky

this.$root.globalVarin any component

N
nzy, 2019-04-09
@nzy

The simplest: And then in the component just use globalVar.

M
MaxVilson, 2020-03-12
@MaxVilson

It is possible to write functions and variables during Vue initialization and access them via $root. For example:
@click="$root.myGlobalMethods"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question