Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use vuex in vue components?

Tags:

vue.js

vuex

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?

like image 482
nagy.zsolt.hun Avatar asked Nov 04 '17 22:11

nagy.zsolt.hun


People also ask

Where do you put Vuex?

This file can be put anywhere. It's generally suggested to put it in the src/store/store. js file, so we'll do that. We export a Vuex store object, which we create using the Vuex.

Is Vuex part of Vue?

Vuex is a state management pattern + library for Vue.

Is pinia better than Vuex?

Pinia has a Simpler API than Vuex Pinia's API is simpler and more intuitive than Vuex. Getting started with state management is much easier even for a junior developer as a lot of boilerplate code that needed to be written between every state change in Vuex has now been removed in Pinia.


1 Answers

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.

like image 137
8bit Avatar answered Sep 18 '22 20:09

8bit