uni-app如何使用vuex(vue2—详)

为方便自身查阅,直接上代码
官网地址:Vuex 是什么? | Vuex (vuejs.org) 
npm下载地址:

npm install vuex@next --save

 根目录新建store->index.js文件

// index.js

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

Vue.use(Vuex);

export default new Vuex.Store({
	state: {
		count: '我很帅'
	},
	mutations: {
		increment(state) {
			state.count++;
		},
		decrement(state) {
			state.count--;
		}
	},
	actions: {
		increment(context) {
			context.commit('increment');
		},
		decrement(context) {
			context.commit('decrement');
		}
	},
	getters: {
		getCount: state => state.count
	}
});

main.js引入

//main.js

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

——————————————————以上引入完成
——————————————————以下使用方法
(以下栗子以index.js文件数据为例)
一、state (管理组件数据,管理的数据是响应式的)
组件调用:this.$store.state.属性名,辅助函数:mapState ,getters调用:this.$store.getters.属性名 ,getters辅助函数也可调用——方法在四
注:辅助函数使用方式

index.vue

import {
		mapState,
		mapGetters,
		mapActions,
		mapMutations
	} from 'vuex' 

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

二、mutations (更新数据,state中的数据只能使用mutations去改变数据—同步) 
组件调用:this.$store.commit ,辅助函数:mapMutations(对象形式可传参)

注:辅助函数使用方式

// index.vue页面

一、对象形式映射 (可传参)

methods: {
            // 事件同级
            // param 为自定义方法名(传参用)
            // activeNumber 为vuex中方法名
			...mapMutations({
				param: 'activeNumber'
			}),
            // 触发纽扣
			dianji() {
				// vuex 辅助函数调用+传参
				this.param(15)
			},
}

二、数组形式映射 (不可传参)

 methods: {
            ...mapMutations([
              'activeNumber', 
            ])
  }

三、action (提交的是 mutation,而不是直接变更状态—异步
组件调用:this.$store.dispatch ,辅助函数:mapActions(对象形式可传参)

//index.vue

methods: {
    handleQuery () {
        // 触发action(必须调用dispatch方法)
        this.$store.dispatch('activeNumber', 111)
       
        // 以载荷形式分发
        this.$store.dispatch('activeNumber', {
          amount: 10
        })

        // 以对象形式分发
        this.$store.dispatch({
          type: 'activeNumber',
          amount: 10
        })
    }

    // 构造函数调用方法和 mapMutations 一致
    // 事件同级
        ...mapActions([
          'activeNumber', // 将 `this.increment()` 映射为`this.$store.dispatch('increment')`
             ]),

    	...mapActions({
			param: 'activeNumber' 
		}),

        dianji() {
				// action 辅助函数
			this.param(15)
		},

}

可以通过action调用处理接口数据后通过commit 传给mutations 

// vuex中代码

actions: {
    // 第一个参数通常为context可以拿到vuex中的dispatch、commit、state、getters...等多项
 GetRoute({ commit, state }, menuKey) {
      return new Promise((resolve, reject) => {
        if (!state.menus) {
          indexMenusApi().then(resp => {
            commit('SET_MENUS', resp.data.data)
          })
        }
        const route = filterRoute(state.menus, menuKey)
        resolve(route)
      })
    },
}

 mutations: {

    SET_MENUS: (state, menus) => {
      state.menus = menus
    },
}

四、getters (可以认为是 store 的计算属性)
组件调用:this.$store.getters.属性名 ,辅助函数:mapGetters

// vuex中
    state: {
        menus:'我很帅',
        todos: [
          { id: 1, text: '...', done: true },
          { id: 2, text: '...', done: false }
        ]
}
    getters: {
        // 可以封装一些共享函数 
         doneTodos (state) {
          return state.todos.filter(todo => todo.done)
        }
        // 也可以在组件中通过mapGetters辅助函数直接使用 
        globalMenus: state => state.menus,
              
}

// 页面中
     computed: {
         ... mapGetters([
           // 可以直接使用
           'globalMenus'
        ])
}

以上完————编写博客时意外点了撤回 差点功夫白费,幸好自带历史回退
 

UniApp是一个基于Vue.js的跨平台开发框架可以用于开发iOS、Android、H5等多个平台的应用程序。而VuexVue.js官方提供的状态管理库,用于集中管理应用程序的状态。 在UniApp使用Vuex可以帮助我们更好地管理应用程序的状态,实现数据的共享和响应式更新。下面是使用Vuex的步骤: 1. 安装Vuex:在UniApp项目的根目录下,使用npm或者yarn安装Vuex。 ``` npm install vuex --save ``` 2. 创建store:在项目的src目录下创建一个store文件夹,并在该文件夹下创建一个index.js文件。在index.js中引入VueVuex,并创建一个新的Vuex.Store实例。 ```javascript import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ // 在这里定义你的状态和相关操作 }) export default store ``` 3. 定义状态和操作:在store文件夹下创建一个modules文件夹,并在该文件夹下创建一个module.js文件。在module.js中定义你的状态和相关操作。 ```javascript const module = { state: { count: 0 }, mutations: { increment(state) { state.count++ } }, actions: { incrementAsync({ commit }) { setTimeout(() => { commit('increment') }, 1000) } } } export default module ``` 4. 在main.js中引入store:在main.js中引入刚刚创建的store,并将其挂载到Vue实例上。 ```javascript import Vue from 'vue' import App from './App' import store from './store' Vue.config.productionTip = false App.mpType = 'app' const app = new Vue({ store, ...App }) app.$mount() ``` 现在,你就可以在组件中使用Vuex了。可以通过`this.$store.state`访问状态,通过`this.$store.commit`调用mutations中的方法,通过`this.$store.dispatch`调用actions中的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值