[Vuejs]-Set variable from component in instance

0๐Ÿ‘

โœ…

This should do the trick:

Vue.component('graph', {
  template: '',
  props: {},
  data: {},
  methods: {
    setBtn: function () {
      app.showBtn = false;
    },
  },
});

var app = new Vue({
  el: '#app',
  data: {
    showBtn: null
  },
  methods: {},
});

0๐Ÿ‘

You can access data on the root vue instance through vm.$root.

setBtn: function () {
   this.$root.showBtn = false;
},

0๐Ÿ‘

As a best practice you should avoid directly setting params on other components. Vue is intended to decouple its components therefore directly editing a param, although possible, runs in the face of this. Check out the components guide for more info, specifically: https://v2.vuejs.org/v2/guide/components.html#Composing-Components

Therefore rather than directly editing this param you should emit an event from the component which you can listen for on the root โ€“ or any other component that sets the graph component, i.e.

graph component emit an event

Vue.component('graph', {
  methods: {
    activateBtn () {
      this.$emit('set-button', true)
    },
    ...

root or any component that sets graph in its template

# template
<graph @set-button="setBtn"></graph>

# script
new Vue({
  el: '#app',
  data: {
    showBtn: false
  },
  methods: {
    setBtn (state) {
      this.showBtn = state
    },
  },
})
  

Leave a comment