1、vuex个人讲解
官方解析是这样的:https://vuex.vuejs.org/zh/
个人觉得最大作用是把网站上各个页面(如购物车页面、结账页面、浏览页面)一些公用变量(最简单的是如购物车上面的商品数量),这些变量希望在各个页面上保持一致,通过把这些变量放在一个容器(store)中,使前端访问修改都是同一个变量(有点全局变量的意思),官方给出vuex定义是“状态管理模式”,很明显vuex最大的亮点是能够调试这些变量的流向,给项目调试带来很多方便(调试方面理解不清楚)
2、实际项目中运用到vuex的地方
毕设的项目(租车管理系统)整体设计还在进行,目前想到vuex可以在项目:①存放网站“全局变量”,想登录状态、权限等级、租车情况。当用户在本页面的模块调转时,可以访问前端store.js的变量就可以知道本页面的登录情况,是否有权限访问,而不用频繁跟后台交互②在store写一些改变变量的方法,当一处改变,单页面的其他模板都能相应得到
3、项目实际代码模板(可以把方法和状态值都放在一个store.js上,数据多是方便处理也可以把他们单独放在几个js上,引用方式差不多)
官方提供了几个核心概念:1、state:下面存放全局数据 2、getter方法:可以用参数取得state的数据 3、Mutation方法:通过在mutation设定具体操作数据方法。可以改变state下面的数据(唯一改变state数据的方法,只能同步执行) 4、Action方法:通过控制mutation,可以达到方法的异步执行(与生命周期有关) 以上在store容器写好的数据和方法,都要在实际vue网页上引入其语句柄(就是触发语句执行的句子),在HTML中绑定或者调用就可以了
在vue项目上建立store.js(相当于一个数据容器)
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// 首先声明一个状态 state,这是存放着‘全局数据’
const state = {
checkpower: 0 //登录权限为0
}
// 然后给 actions 注册事件处理函数,当这个函数被触发时,将状态提交到 mutaions中处理,(可以直接炒作mutation,不用经过action调用)
const actions = {
inchecklogin: ({ commit }) => commit('inchecklogin'),
}
// 更新状态
const mutations = {
inchecklogin (state) {
state.checklogin += 1
} //通过修改参数,增加权限
}
// 获取状态信息
const getters = {
}
// 下面这个相当关键了,所有模块,记住是所有,注册才能使用
export default new Vuex.Store({
state,
mutations,
actions,
getters
})
至此写好store,写vue页面,引用store参数
<!--这是testpower.vue 子模块页面-->
<template>
<div>
<p>购物车登录状态是: {{$store.state.checklogin}}</p>
<!--这里可以直接显示state的变量-->
</div>
</template>
<script>
import { mapState} from 'vuex' //引入store的mapstate
export default {
name: "testpower",
//用mapState方法绑定语句句柄
computed: mapState([
'checklogin'
]),
}
</script>
<style scoped>
</style>
<!--这是testcheckpower.vue 父模块页面-->
<template>
<div id="app">
登录权限是: {{$store.state.checklogin}}
<button @click="inchecklogin">增加权限</button>
<testpower></testpower>
</div>
</template>
<script>
import testpower from './testpower'
import { mapActions,mapMutations } from 'vuex'
export default{
computed: mapGetters([//与vuex中的getters关联
]),
methods: mapActions([//与vuex中的actions关联
'inchecklogin'
]),
components:{
'testpower': testpower
},
}
</script>
<style scoped>
</style>
只修改一个页面的引用数据,其他页面的数据也跟着响应
vuex状态管理来管理http请求
store 新建device模块
//在 /device/action.js 下
import ajax from "../ajax"; //封装后的axios 请求
const actions = {
// 获取信息
getData ({commit},params) {
return ajax.post(''/business/deviceSn/searchServiceContact'', params)
},
}
export default actions
vuex store目录引入device模块
import Vue from 'vue';
import Vuex from 'vuex';
import device from './device'; //引入device模块
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
device,
},
});
在vue页面中应用:
import { mapActions } from "vuex";
methods: {
...mapActions({
getData: "device/getData", //命名方法:getData 引用于store目录:device/getData
}),
//获取数据http请求 store 封装了一个axios的异步请求
getDate(params).then(res=>{})