repertor
repertor

Reputation: 141

Trigger store action from outside vue app

I want to include buttons in various places on a page, outside the Vue components elsewhere on the page, that trigger store actions through a click event. I have buttons within my components that do as much, connecting to methods after v-on:click that then trigger store actions through this.$store.dispatch. Is it possible to do this from outside of Vue?

Upvotes: 0

Views: 1120

Answers (1)

Ohgodwhy
Ohgodwhy

Reputation: 50767

To directly answer your question, you can do what you want by hanging your Vue instance directly off of the window, for instance:

<div id="app">
  <p>{{ message }}</p>
</div>
window.IVue = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!'
  },
  store: new Vuex.Store({
    actions: {
      hello() {
        return Promise.resolve('Hello from the store!')
      }
    }
  })
})

window.IVue.$store.dispatch('hello').then((message) => {
  Vue.set(window.IVue, 'message', message)
})

And here's a jsFiddle

You'll see the message is Hello from the store!

Upvotes: 1

Related Questions