Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js and vuex: this.$store is undefined

Tags:

I have already read the question with similar titles but I cannot follow them due to their complexity. I think with my code it will be easier to find a solution for me. I will only include the relevant code.

My store is this: obs: I installed the vuex plugin.

   import Vue from 'vue'; import Vuex from 'vuex';   Vue.use(Vuex)  const state = {     titulo: "please, change title" }   const mutations = {     changeTitle(state, title) {         state.title= title     } }   export default new Vuex.Store({      state : state,     mutations : mutations }) 

My App.vue

 <template>     <div>       <show-title-component ></show-title-component>       <change-title-component></change-title-component>     </div> </template>  <script>   import ShowTitleComponent from './components/ShowtitleComponent'; import ChangeTitleComponent from './components/ChangeTitleComponent'; import store from './vuex/store';  export default {  components: {ShowTitleComponent, ChangeTitleComponent}, store, data: function() {   return {title: 'placeholder'} }   } </script> 

The component that generates the error:

<template><div>{{ title}}</div></template>  <script>  export default {     name: "show-title-component",     computed: {       title() {         return this.$store.state.title   /** error   here */       }     } }  </script> 
like image 292
Diego Alves Avatar asked Dec 14 '17 13:12

Diego Alves


People also ask

Is Vuex compatible with Vue 3?

The functionality of most plugins could be replicated with the Composition API, but Vuex does this better and with a more organized structure. The short answer is: Yes. Vuex is the preferred state management solution for Vue apps, and Vuex 4 is the version compatible with Vue 3.

Does Vuex work with Vue 2?

You are using Vuex 4 which works with Vue 3 only. For Vue 2, you must use Vuex 3.

What is the store in Vuex?

A "store" is basically a container that holds your application state. There are two things that make a Vuex store different from a plain global object: Vuex stores are reactive. When Vue components retrieve state from it, they will reactively and efficiently update if the store's state changes.


1 Answers

Maybe, you have not included the store inside the Vue instance

Your App entry point (app.js or main.js or index.js) must include this code:

import store from './store'  new Vue({  ...  store,  ... }) 

then you can use this.$store in any component

but I recommend the general architecture: https://vuex.vuejs.org/en/structure.html enter image description here

like image 200
Volodymyr Symonenko Avatar answered Sep 18 '22 06:09

Volodymyr Symonenko