Bootstrap

uniapp 如何使用vuex store (亲测)

首先是安装:

npm install vuex@next --save

安装之后,Vue2 这样写

不管在哪里,建立一个JS文件,假设命名:store.js

代码这样写:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
	  battery: {}
	  
	  	
	  

  }, 
  mutations: {
	  SET_BATTERY_INFO(state, info) {
	  	state.battery = info;
	  }
	 
  },
   getters : {
  	getBatteryInfo: state => state.battery,
	
   },
  actions: {},
 
})

export default store

这里面的SET方法,自己去改成自己的哈

然后在main.js中这样写:

import store from 'request/store/store.js'
Vue.prototype.$store = store

const app = new Vue({
  ...App,
  store
})
app.$mount()

然后在其他JS文件中这样使用:

import store from './store/store' //需要先导入

store.commit('SET_CHASSIS_INFO', message)//使用store就可以进行访问变量

在其他的vue界面这样用:

首先写你需要的变量

computed:{
			...mapState(['battery'])
		},

然后在页面中这样写:

<view class="bottomtext">{{battery.args.soc}}%</view>

我这个battery是一个对象

在方法中这样使用:

this.$store.state.battery

有不对的,希望大家指正,共同进步!

;