小程序如何使用vuex 状态管理工具

106 阅读1分钟

首先 npm i vuex 下载

然后去根目录创建store文件夹,index.js文件

// 引入vue 和vuex
import Vue from 'vue'
import Vuex from 'vuex'

// 将vuex安装为vue的插件
Vue.use(Vuex)

// 创建store实例
const store = new Vuex.Store({
  state:{
    msg:123
  },
  mutations:{},
  actions:{},
  getters:{}
})

// 向外共享store实例对象
export default store

2.然后去main.js


// 导入store实例 文件
import store from './store/index.js'const 将store实例挂载到vue实例上就可以用了

const app = new Vue({
    ...App,
    // 将store实例 挂载到vue 实例上
    store
})

使用时:

import { mapState } from 'vuex';

computed:{
  ...mapState(['msg'])
},
页面中{{msg}}使用即可