0
votes

I know that is supersimple to access and set Vue instance properties if it is done like that:

var vm1 = new Vue({
    el: '#vm1',
    data: {
        name: 'Vue Instance #1'
    }
});

Then we can do something like vm1.whatever = 1

(example is taken from here: https://codingexplained.com/coding/front-end/vue-js/accessing-vue-instance-outside-declaration)

But what if we do it in a more normal way:

import Vue from 'vue'
import App from './App.vue'

new Vue({
  render: h => h(App)
}).$mount('#rank_app')

What is the way to set some data externally? I found very ugly way:

import Vue from 'vue'
import App from './App.vue'

window.rankVue = new Vue({
  render: h => h(App)
}).$mount('#rank_app')

and then I can set the data from outside by: window.rankVue.$children[0].error= true;

I wonder if there are less ugly solutions. (I am aware that it is a bad practice, but believe me there is no other way - I am in Django, and templates + form to submit is provided not by me, so I need to change error variable used to render vue instance when the form submitted etc.)

1

1 Answers

1
votes

With this example:

You need to define a method or methods to update the internal state of your component.

With refs you can specify the child component you want to update (it replaces $children).

Vue.component('board',{
    render: function (createElement) {
      return createElement('div',
       this.text
      )
    },
    data(){
      return {
          text: 'Vue Instance #1'
      }
    }
});

var myInstance = new Vue({
  el: '#rank_app',
  template: "<div> <h1>Example</h1> <br/> <board ref='message'/></div>",
  methods: {
    setError(errorMessage) {
      this.$refs['message'].text = errorMessage
    }
  }
});

function changeValue() {
  myInstance.setError("From outside")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="rank_app"></div>

<button onclick="changeValue()"> Change value </button>

You can improve it, using Vuex. Where the state is managed by Vuex, and you don't need to lead with the components structure.