I have one module(javascript file) outside of vue context. i need to dispatch action from this javascript file. is it possible ? if yes, then how ?
jsfile.js(Javascript file)
const detail = {};
detail.validateLocation = (location) => {
// need to dispatch one action from here.
// dispatch('SET_LOCATION', {city: 'California'})
// how to dispatch action ?
}
export default detail;
action.js
export default {
SET_LOCATION: ({ commit}, data) => {
commit('SET_LOCATION', data);
},
}
store.js
import Vue from 'vue';
import Vuex from 'vuex';
import actions from './actions';
import mutations from './mutations';
import getters from './getters';
export function createStore() {
return new Vuex.Store({
modules: {},
state: {
location: null
},
actions,
mutations,
getters,
});
}
There are two ways to import a JavaScript library to the Vue Component. The first is to import a local JavaScript library. Here, you can import the JavaScript library by using the 'import' keyword inside the script tag of your Vue file. import * as mykey from '../assets/js/mykey.
You can call another Vuex action by passing the name of that action as a string as the first argument of dispatch : const store = new Vuex. Store({ actions: { walk(context) { context. dispatch("goForward"); }, goForward(context) { // }, }, });
In Vue. js, components can be written in HTML, CSS, and JavaScript without dividing them into separate files.
$dispatch sends a message to your vuex store to do some action. The action may be done anytime after the current tick, so that your frontend performance is not affected. You never commit from any of your components / routes. It is done only from within an action, and only when you have some data to commit.
First, create the store in store.js.
import Vue from 'vue';
import Vuex from 'vuex';
import actions from './actions';
import mutations from './mutations';
import getters from './getters';
const store = new Vuex.Store({
modules: {},
state: {
location: null
},
actions,
mutations,
getters,
});
export default store
Then, import the store into jsfile.js and use it.
import store from "./store"
const detail = {};
detail.validateLocation = (location) => {
// Use imported store
store.dispatch('SET_LOCATION', {city: 'California'})
}
export default detail;
Assuming you have a main or index file that creates your Vue instance, you now likely need to change the import from importing the create function to simply importing the store.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With