uni-app引入vuex状态管理

1、引入vuex,在项目根目录创建文件夹store,并创建文件index.js(uni-app有内置了vuex,所以直接引入就可以了)
uni-app引入vuex状态管理_第1张图片
2、在全局入口文件main.js引入Vuex

import Vue from 'vue'
import App from './App'
//引入vuex
import store from './store'
//把vuex定义成全局组件
Vue.prototype.$store = store
Vue.config.productionTip = false

App.mpType = 'app'

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

3、在store.js定义内容,ApiRequest.js文件看附件代码

import Vue from 'vue';
import Vuex from 'vuex';
import ApiRequest from '../utils/ApiRequest.js';

Vue.use(Vuex);

const store = new Vuex.Store({
    modules: {},
    //state:定义属性
    state: {
		resInfo:{} // 基本信息
    },
    //可以动态改变state属性值的内容
    mutations: {
		setResInfo(state,data){
			state.resInfo= data || {}
		}
    },
    //异步获取目标数据后传到mutations,由其操作,使他处可以调用state属性值
    actions: {
		getResInfo: async function (context, token) {
            return await new Promise((resolve, reject) => {
                ApiRequest.get('/user/info').then((res) => {
                	//引用mutations定义的函数,将接口获取到的数据赋给其data参数
                    context.commit('setResInfo', res.data);
                    resolve(res);
                });
            });
    },
});
export default store;
//附件
import store from '@/store'
const Fly = require('flyio/dist/npm/fly');
let http = new Fly();

http.config = {
    parseJson: true,
    timeout: '1500000',
};

http.interceptors.request.use((request) => {
    request.baseURL = store.state.baseURL;
    request.headers['Authorization'] = store.state.Authorization || '';
    uni.showLoading({
        title: '加载中',
    });
    return request;
});

http.interceptors.response.use(
    (response) => {
        uni.hideLoading();
        if (response.status != 200) {
            uni.showToast({
                title: response.statusText,
                icon: 'none',
                mask: true,
                duration: 3000,
            });
        } 
        if (response.data.code != 200) {
            //业务数据处理失败
            if(response.data.msg){
                uni.showToast({
                    title: response.data.msg,
                    icon: 'none',
                    mask: true,
                    duration: 3000,
                });
            }
        } 
        return response.data;
    },
    (err) => {
        uni.hideLoading();
        uni.showToast({
            title: err.message,
            icon: 'none',
            mask: true,
            duration: 3000,
        });
        //发生网络错误后会走到这里
    }
);

const fetch = http;

export default fetch;

4、要想拿到数据就要先调用store.js里面的actions模块的getResInfo并执行,只有这样,store仓库才有数据。仓库有数据后,我们就可以任意调用了。

//获取=>存储
mounted(){
	//使用this.$store.dispatch调用getResInfo执行获取数据并存进仓库
	this.$store.dispatch('getResInfo');
},
//2、使用仓库值
//方法一:使用this.$store.state直接调用
export default {
	data () {
		return {
			data:this.$store.state.resInfo;
		}
	}
}
//方法二:
import { mapState } from 'vuex';//1.引入mapState
export default {
	data () {
		return {
			...mapState(['resInfo']),//2.接着引入resInfo
			data:this.resInfo['name'];//3.再接着调用resInfo
		}
	}
}

你可能感兴趣的:(vue.js,javascript,uni-app)