15

I have a vuex example project:

app.vue:

<template>
    <div>{{message}}</div>
</template>

<script>
import store from "./app.store.js";

export default {
    computed: { message: () => store.message }
}
</script>

app.store.js:

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

const state = { message: "Hello World" };
const getters = { message: state => state.message };
const store = new Vuex.Store({ state, getters });

export default store;

The {{message}} placeholder is replaced with empty string instead of "Hello World". How to use vuex in vue components?

1 Answer 1

14

First, make sure to include the store in your Vue instance, as in:

new Vue({ el: '#app', store });

Also, in the computed property, don't access the store directly (although it is perfectly fine), use the getter you created.

And now when you inject the store in the Vue instance, it is automatically available to all of your child components - meaning you don't need to import it, rather just use it like this in your component:

computed: { return this.$store.getters.message }

You can read more on the topic here.

Sign up to request clarification or add additional context in comments.

2 Comments

Passing the store object to the Vue constructor makes the "this.$store" variable available in components. However, I prefer using arrow functions, where the "this" reference is not available - so I import the store in each vue component. The store object in the Vue constructor is optional this way. The issue with my code was the missing .getters reference.
Oh my gosh @nagy.zsolt.hun, I have been banging my head all over the internet trying to find out why commit doesn't exist as a property of this.$store then I remembered after your comment the arrow function doesn't include "this"! and I used count: () => { instead of count () { You're the best!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.