1. 安装
npm install vuex --save
2. 简单示例
(1)src/vuex/store.js中写入以下代码:
// 引入vue import Vue from 'vue' // 引入vuex import Vuex from 'vuex' // 使用vuex Vue.use(Vuex) // 1、state:创建初始化状态 const state = { // 放置初始状态 count: 1 } // 2、mutations:创建改变状态的方法 const mutations = { // 状态变更函数-一般大写 ADD (state, n) { state.count += n; } } // 3、getters:提供外部获取state const getters = { count: function(state){ return state.count; } } // 4、actions:创建驱动方法改变mutations const actions ={ // 触发mutations中相应的方法-一般小写 add ({commit}, data) { commit('ADD', data) } } // 5、全部注入Store中 const store = new Vuex.Store({ state, mutations, getters, actions }); // 6、输出store export default store;
代码说明:
state - mutations - getters - actions - store,以上写法基本固定。
小型项目用上面的简单管理状态即可。
(2)src/main.js代码中
mport Vue from 'vue' import App from './App' import router from './router' // 引入store import 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>