1、安裝
npm install vuex --save
2、簡單示例
(1)src/vuex/store.js中寫入以下代碼:
// 引入vueimport Vue from 'vue'// 引入vueximport Vuex from 'vuex'// 使用vuexVue.use(Vuex)// 1、state:創建初始化狀態const state = { // 放置初始狀態 count: 1}// 2、mutations:創建改變狀態的方法const mutations = { // 狀態變更函數-一般大寫 ADD (state, n) { state.count += n; }}// 3、getters:提供外部獲取stateconst getters = { count: function(state){ return state.count; }}// 4、actions:創建驅動方法改變mutationsconst actions ={ // 觸發mutations中相應的方法-一般小寫 add ({commit}, data) { commit('ADD', data) }}// 5、全部注入Store中const store = new Vuex.Store({ state, mutations, getters, actions});// 6、輸出storeexport default store;
代碼說明:
state - mutations - getters - actions - store,以上寫法基本固定。
小型項目用上面的簡單管理狀態即可。
(2)src/main.js代碼中
import Vue from 'vue'import App from './App'import router from './router'// 引入storeimport store from './vuex/store'Vue.config.productionTip = false/* eslint-disable no-new */new Vue({ el: '#app', router, store, // 全局注入 components: { App }, template: '<App/>'})
(3)src/compontent/Count.vue頁面組件中代碼如下:
<template> <div class="hello"> <h1>{{ msg }}</h1> <h2>{{count}}</h2> <button @click="clickAdd">新增</button> </div></template><script>export default { data () { return { msg: 'Vuex test!' } }, computed: { // 獲取state值 count() { return this.$store.state.count; } }, methods: { clickAdd() { //分發action中的add方法 this.$store.dispatch('add', 1); } }}</script><style scoped></style>