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?
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.
Vuex is a state management pattern + library for Vue.
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.
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.
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