How to add Vuex to Vue project
Vue 2
npm install [email protected] --save
Create file: src/store/index.js
// store/index.js
import Vuex from 'vuex'
import Vue from 'vue'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
})
export default store
In src/main.js
:
// src/main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from "@/store"; // add this line
import './assets/main.css'
new Vue({
router,
store, // add this line
render: (h) => h(App)
}).$mount('#app')
Vue 3
npm install vuex@next --save
Create file: src/store/index.js
import { createStore } from 'vuex'
export default createStore({
state () {
return {
count: 0
}
},
mutations: {
increment (state) {
state.count++
}
}
})
In src/main.js
:
import {createApp} from 'vue'
import App from './App.vue'
import router from './router'
import store from '@/store'; // add this line
import './assets/main.css'
const app = createApp(App)
app
.use(router)
.use(store) // add this line
app.mount('#app')
Using the store
With options API:
function closeModal() {
this.$store.state.isOpen = false
}
With composition API
import {useStore} from "vuex";
const store = useStore()
function closeModal() {
store.state.isOpen = false
}