【vue2 vuex】store state mutations actions状态管理(草稿一留存)

@/store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import {
	mdUserMsglist
 } from "@/api/index/index.js"
Vue.use(Vuex); //vue的插件机制
const store = new Vuex.Store({
	// state 表示 需要共享的状态数据
	state: {
		msg: uni.getStorageSync('ismsg'), // 是否有新消息 true是 false否
	},
	/*
		1. mutations 表示 更改 state的方法集合 只能是同步更新 不能写ajax等异步请求
		2. 异步操作,通过mutations来改变state。
		3.包含多个事件回调函数的对象。
		4. 执行方式:通过执行 commit()来触发 mutation 的调用, 间接更新 state
		5.触发方式: 组件中: $store.dispatch(‘action 名称’, data1)
	*/ 
	mutations: {
		// 更新数据
		uploadMsg(state, msgdata) {
			state.msg = msgdata;
		},
	},
	// actions 将对应的网络请求数据放在这里来操作 可以在actions中发起 然后提交给 mutations mutation再做同步更新
	actions: {
		// 请求数据
		getMsg(){
			console.log('请求数据11')
			if(!uni.getStorageSync('id')){ return }
			let data = {
				userId: uni.getStorageSync('id')
			}
			let isnew = false;
			mdUserMsglist(data).then(res => {
				console.log('actions 请求数据 ',res.rows)
				res.rows.forEach(item => {
					if(item.status == 0){
						isnew = true;
					}
				});
				context.commit("uploadMsg",isnew) //拿到数据传入进去
			});
		}
		
	}
})
export default store

main.js

import store from 'store/index.js'

import Vue from 'vue'
App.mpType = 'app'
const app = new Vue({
    ...App,
	store
})
app.$mount()

你可能感兴趣的:(vue.js,前端,javascript)