Cannot find declaration to go to Vuex WebStorm? - vuex

I added auto import Vuex modules and after that I can't go to Vuex actions/getters/etc from component or another place where I declared.
Now my architecture like this:
index.ts
store
module1.store.ts
module2.store.ts
module3.store.ts
index.ts
store/index.ts:
const requireModule = require.context('.', false, /\.ts$/)
const modules: any = {}
requireModule.keys().forEach(fileName => {
if (fileName === './index.ts') return
const moduleName = fileName
.replace(/(\.\/|\.store\.ts)/g, '')
.replace(/^\w/, c => c.toLowerCase())
modules[moduleName] = requireModule(fileName).default || requireModule(fileName)
})
export default modules
index.ts (sibling store):
export default new Vuex.Store({
modules,
strict: debug,
plugins: debug ? [createLogger()] : []
})
If I use anybody action in component It's work but If I want to go this action from component I can't:
Every store module has:
export default {
namespaced: true,
state,
actions,
getters,
mutations
}

Vuex completion in WebStorm is based on the static code analysis. Unfortunately the syntax used by you is too complex to be statically analyzed, as the module name is dynamically produced from the file name.
Please see comments in WEB-45228 for possible workarounds

Related

Vue.js Vuex cannot access store in router

I've seen that this question have been asked a couple of time but I cannot find any good answer and don't understand why my code is behaving like this.
As said in the title I'm trying to import my store in the router to be able to use my getters on conditional and grant a user to access or not a route.
But as soon as i'm trying to import the store I get the following error:
[vuex] unknown action type: autoSignIn
this is coming from:
const vm = new Vue({
router,
store,
provide,
i18n,
render: handle => handle(App),
created () {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.$store.dispatch('autoSignIn', user)
this.$store.dispatch('loadMatter')
this.$store.dispatch('loadFootprints')
this.$store.dispatch('loadMembers')
}
})
So I guess that when my app is starting the store hasn't loaded yet.
How can I workaround that I want to be able to use
store.getters.mygetter
Thank you very much
I think you need to import your store in your router file
I'm doing it like this:
import store from "#/store/index.js";
Are you using modules of vuex?
Can you share your store index file?
https://vuex.vuejs.org/guide/modules.html
If you are using modules of vuex, you should do this.$store.dispatch('module_name/action_name')
I have my store split into files
Vue.use(Vuex);
const store = new Vuex.Store({
state,
actions,
mutations,
getters,
plugins: [
process.env.NODE_ENV === 'development' && createLogger({ collapsed: false }),
].filter(Boolean),
});
export default store;

nuxtServerInit in Modules mode does not run

I'm using nuxt.js in Universal mode and i'm trying to run nuxtServerInit() in one of my store actions, however it is not running.
In the docs it says...
If you are using the Modules mode of the Vuex store, only the primary
module (in store/index.js) will receive this action. You'll need to
chain your module actions from there.
However I don't quite understand what you need to do in order to make this work. Also if you need to use the primary module, then why would you need to use the module mode at all? Then you should just need to use the Classic mode.
store/posts.js
export const state = () => ({
loadedPosts:[]
});
export const getters = {
get(state){
return state
}
};
export const mutations = {
setPosts(state, payload){
state.loadedPosts = payload;
}
};
export const actions = {
async nuxtServerInit ({commit}){
const {data} = await axios.get('somedata')
console.log('I cannot see this comment');
commit('setPosts', data.results)
}
};
As it says in the documentation, you really need to have that function in the index.js file inside the store folder, which will not work otherwise.
here's an example of a production NuxtJs universal application with the ./store/index.js only with that file, you can easily call other stores methods by prefixing them with the file name, as the example shows auth/setAuth
I just faced the problem that nuxtServerInit was not called. The reason was in nuxt.config.js where ssr was set to false.
nuxt.config.js
export default {
// Disable server-side rendering: https://go.nuxtjs.dev/ssr-mode
// ssr: false, <-- Remove or out comment the line
/*
** Nuxt target
** See https://nuxtjs.org/api/configuration-target
*/
target: 'server',
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
}
}

Vue/Nuxt: How to define a global method accessible to all components?

I just want to be able to call
{{ globalThing(0) }}
in templates, without needing to define globalThing in each .vue file.
I've tried all manner of plugin configurations (or mixins? not sure if Nuxt uses that terminology.), all to no avail. It seems no matter what I do, globalThing and this.globalThing remain undefined.
In some cases, I can even debug in Chrome and see this this.globalThing is indeed defined... but the code crashes anyway, which I find very hard to explain.
Here is one of my many attempts, this time using a plugin:
nuxt.config.js:
plugins: [
{
src: '~/plugins/global.js',
mode: 'client'
},
],
global.js:
import Vue from 'vue';
Vue.prototype.globalFunction = arg => {
console.log('arg', arg);
return arg;
};
and in the template in the .vue file:
<div>gloabal test {{globalFunction('toto')}}</div>
and... the result:
TypeError
_vm.globalFunction is not a function
Here's a different idea, using Vuex store.
store/index.js:
export const actions = {
globalThing(p) {
return p + ' test';
}
};
.vue file template:
test result: {{test('fafa')}}
.vue file script:
import { mapActions } from 'vuex';
export default {
methods: {
...mapActions({
test: 'globalThing'
}),
}
};
aaaaaaaaand the result is.........
test result: [object Promise]
OK, so at least the method exists this time. I would much prefer not to be forced to do this "import mapActions" dance etc. in each component... but if that's really the only way, whatever.
However, all I get is a Promise, since this call is async. When it completes, the promise does indeed contain the returned value, but that is of no use here, since I need it to be returned from the method.
EDIT
On the client, "this" is undefined, except that..... it isn't! That is to say,
console.log('this', this);
says "undefined", but Chrome's debugger claims that, right after this console log, "this" is exactly what it is supposed to be (the component instance), and so is this.$store!
I'm adding a screenshot here as proof, since I don't even believe my own eyes.
https://nuxtjs.org/guide/plugins/
Nuxt explain this in Inject in $root & context section.
you must inject your global methods to Vue instance and context.
for example we have a hello.js file.
in plugins/hello.js:
export default (context, inject) => {
const hello = (msg) => console.log(`Hello ${msg}!`)
// Inject $hello(msg) in Vue, context and store.
inject('hello', hello)
// For Nuxt <= 2.12, also add 👇
context.$hello = hello
}
and then add this file in nuxt.config.js:
export default {
plugins: ['~/plugins/hello.js']
}
Use Nuxt's inject to get the method available everywhere
export default ({ app }, inject) => {
inject('myInjectedFunction', (string) => console.log('That was easy!', string))
}
Make sure you access that function as $myInjectedFunction (note $)
Make sure you added it in nuxt.config.js plugins section
If all else fails, wrap the function in an object and inject object so you'd have something like $myWrapper.myFunction() in your templates - we use objects injected from plugins all over the place and it works (e.g. in v-if in template, so pretty sure it would work from {{ }} too).
for example, our analytics.js plugin looks more less:
import Vue from 'vue';
const analytics = {
setAnalyticsUsersData(store) {...}
...
}
//this is to help Webstorm with autocomplete
Vue.prototype.$analytics = analytics;
export default ({app}, inject) => {
inject('analytics', analytics);
}
Which is then called as $analytics.setAnalyticsUsersData(...)
P.S. Just noticed something. You have your plugin in client mode. If you're running in universal, you have to make sure that this plugin (and the function) is not used anywhere during SSR. If it's in template, it's likely it actually is used during SSR and thus is undefined. Change your plugin to run in both modes as well.
This would be the approach with Vuex and Nuxt:
// store/index.js
export const state = () => ({
globalThing: ''
})
export const mutations = {
setGlobalThing (state, value) {
state.globalThing = value
}
}
// .vue file script
export default {
created() {
this.$store.commit('setGlobalThing', 'hello')
},
};
// .vue file template
{{ this.$store.state.globalThing }}

How can I break my Vuex actions into multiple files and still use `dispatch`?

I have broken my actions into multiple files to make my project more maintainable and extensible. Trying to dispatch from one action to another, however, is not working.
My file tree looks like this:
store.js
actions
|--actions.js
|--createShape.js
|--addShape.js
My store.js looks like:
import actions from './actions/actions'
const PlaypadStore = {
namespaced: true,
state: {
localState: ''
},
actions: {
...actions,
},
}
My actions.js folder has the following:
import CREATE_SHAPE from './createShape';
import ADD_SHAPE from './addShape';
export default {
CREATE_SHAPE,
ADD_SHAPE,
}
The problem is trying to dispatch ADD_SHAPE from CREATE_SHAPE. My createShape.js looks like the following:
const CREATE_SHAPE = ({ state, dispatch }) => {
return dispatch('ADD_SHAPE')
}
export default CREATE_SHAPE;
But it returns me this:
[vuex] unknown local action type
The question is this: how can I break my actions into multiple files, but still be able to dispatch actions from one to another?
if you use 'export default...' in your action-files and import your files in the store like that:
import actions_one from './actions_one';
import actions_two from './actions_two';
you can then use the spread operator to make it like you're importing one object:
export default new Vuex.Store({
namespaced: true,
actions: {
...actions_one,
...actions_two
},
...
you need to let Vuex know that actions.js, createShape.jsand addShape.jsare "modules" of your store for this to work.
You can read more about it in the Vuex Modules documentation.
Basically you need an index.js file declaring the modules at the root of your store. That should look like this:
import actions from "./actions";
import createShape from "./createShape";
import addShape from "./addShape";
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
actions,
createShape,
addShape
}
});
At this point your dispatch call should work, UNLESS it comes from another vuex store module, in that case just specify "root = true" as they pointed out here.

Vuex module not accessible from rootState

I needed to get route's query parameters inside Vuex in order to preload filter settings and update the state of the application. To make this possible I installed vuex-router-sync.
Next step was to synchronize the Vuex and VueRouter.
Router:
Vue.use(VueRouter);
export default new VueRouter({ mode: 'history' });
Store:
Vue.use(Vuex);
export default new Vuex.Store({
modules: { filters: FiltersModule },
plugins: [ FiltersPlugin ]
});
App's bootstrap:
const unsync = sync(store, router);
new Vue({
el: '#restaurant-admin-app',
components: {
'App': AppComponent,
'filters': FilterComponent,
'orders-table': OrdersTableComponent
},
store,
router
});
My FilterPlugin that should trigger the URL parsing:
export default store => {
store.dispatch('filters/parseURLFilterSettings');
}
And now, the funny part, here's the URL parsing action:
parseURLFilterSettings: ({ state, commit, rootState }) {
console.log('RootState:', rootState);
console.log('Route module (incorrect):', rootState.route);
console.log('Filters module (correct):', rootState.filters);
console.log('Object\'s keys:', Object.keys(rootState));
}
What am I doing wrong? I thought it might be something with syncing, but at the end the console.log shows clearly that the route Object is there (and it's not empty), but somehow when I access it, it's undefined. Thank you in advance.
The problem was very well explained here. What it basically says is that the object's value is evaluated when you open it's body in the console.
The problem was I didn't have the route module loaded yet, because I was trying to dispatch an action from a vuex plugin which seems to load before the vuex-router-sync's syncing was done.
The problem was solved when I moved application's bootstrap logic from vuex plugins into the AppRootComponent's mount lifecycle event.
You should import the router-sync. After that your store and routes wil behave properly. I usually do this in the main.js file.
import router from './router'
import store from './store'
import { sync } from 'vuex-router-sync'
sync(store, router)