uni-app已經內置了vuex,所以只要正確引入就好了。
1、根目錄創建store文件存放vuex
2、創建index.js
導入vue和vuex
import Vue from 'vue' import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({ state: { city:'城市名', login:false }, mutations: { ShowGood(){ console.log('that is good!!!') } }, actions: {} })
export default store
3、main.js入口文件
// 引入store import store from './store' // 把vuex定義成全局組件 Vue.prototype.$store = store
導入輔助函數
import { mapState, mapMutations } from 'vuex'
使用
computed: { ...mapState(['login', 'city']) },
methods: { change(e) { this.current = e.detail.current; }, ...mapMutations(['ShowGood']) }