目录
今日目标:
- Vuex简介
- Vuex的核心组成
- Vuex版本问题及store.js的使用
- Vuex中的设置及获取变量值
- Vuex中的异步同步操作
- Vuex后台交互及总结
一、Vuex简介
官方解释:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。可以想象为一个“前端数据库”(数据仓库),
让其在各个页面上实现数据的共享包括状态,并且可操作
Vuex分成五个部分:
- State:单一状态树
- Getters:状态获取
- Mutations:触发同步事件
- Actions:提交mutation,可以包含异步操作
- Module:将vuex进行分模块
官方图解Vuex :
二、Vuex中的各个js文件的用途
变量传值的演变形式
图解Vuex各组件:那四个加起来才是vuex
vue中各个组件之间传值
1.父子组件
父组件-->子组件,通过子组件的自定义属性:props
子组件-->父组件,通过自定义事件:this.$emit('事件名',参数1,参数2,...);
2.非父子组件或父子组件
通过数据总数Bus,this.$root.$emit('事件名',参数1,参数2,...)
3.非父子组件或父子组件
更好的方式是在vue中使用vuex
方法1: 用组件之间通讯。这样写很麻烦,并且写着写着,估计自己都不知道这是啥了,很容易写晕。
方法2: 我们定义全局变量。模块a的数据赋值给全局变量x。然后模块b获取x。这样我们就很容易获取到数据
三、准备工作
1. vuex使用步骤
1.1 安装
- npm install vuex -S (下载最新版本的vuex依赖)
- npm i -S [email protected]
1.2 创建store模块
- store
- index.js
- state.js
- actions.js
- mutations.js
- getters.js
这里要注意我们写了一个index.js,把其他js组件挂载到该store文件里面,那么我们要在main.js进行注册挂载
目录结构:
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import getters from './getters'
import actions from './actions'
import mutations from './mutations'
Vue.use(Vuex)
const store = new Vuex.Store({
state,
getters,
actions,
mutations
})
export default store
main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
// process.env.MOCK 为 false ,那么require('@/mock') 不执行的;process.env.MOCK在生产环境下为false
// process.env.MOCK && require('@/mock') //开发环境下才会引入mockjs
// 引入elementUI
import ElementUI from 'element-ui' // 新添加 1
import 'element-ui/lib/theme-chalk/index.css' // 新添加 2 ,避免后期打包样式不同,要放在import App from './App'; 之前
import App from './App'
// 1.引入vue的路由依赖 已有
import router from './router'
import axios from '@/api/http' //#vue项目对axios的全局配置
// import axios from 'axios'
import VueAxios from 'vue-axios'
import store from './store'
Vue.use(VueAxios,axios)
Vue.use(ElementUI) // 新添加 3 使用ElemenUI
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
// 5.挂载 已有
router,
store,
data(){
return {
// 在vue根实例中定义变量,这个变量就是vue实例,它总线
// props this.$emit
Bus:new Vue({
})
}
},
components: { App },
template: '<App/>'
})
四、vuex的核心概念
store、state、getters、mutations、actions
4.1 store
每一个Vuex应用的核心就是store(仓库),store基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。
const store = new Vuex.Store({
state, // 共同维护的一个状态,state里面可以是很多个全局状态getters, // 获取数据并渲染
actions, // 数据的异步操作
mutations // 处理数据的唯一途径,state的改变或赋值只能在这里
})
4.2 state(保存数据的容器)
状态,即要全局读写的数据
const state = {
resturantName:'飞歌餐馆'
};
this.$store.state.resturantName;//不建议
4.3 getters(getXxx)
获取数据并渲染,
const getters = {
resturantName: (state) => {
return state.resturantName;
}
};注1:getters将state中定义的值暴露在this.$store.getters对象中,我们可以通过如下代码访问
this.$store.getters.resturantName注2:state状态存储是响应式的,从store实例中读取状态最简单的方法就是在计算属性中返回某个状态,如下:
computed: {
resturantName: function() {
return this.$store.getters.resturantName;
}
}
4.3 mutations(setXxx)
处理数据的唯一途径,state的改变或赋值只能在这里
export default {
// type(事件类型): 其值为setResturantName
// payload:官方给它还取了一个高大上的名字:载荷,其实就是一个保存要传递参数的容器
setResturantName: (state, payload) => {
state.resturantName = payload.resturantName;
}
}注1:mutations中方法的调用方式
不能直接调用this.$store.mutations.setResturantName('KFC'),必须使用如下方式调用:
this.$store.commit(type,payload);// 1、把载荷和type分开提交
store.commit('setResturantName',{
resturantName:'KFC'
})// 2、载荷和type写到一起
store.commit({
type: 'setResturantName',
resturantName: 'KFC'
})
注2:一定要记住,Mutation 必须是同步函数。为什么呢?异步方法,我们不知道什么时候状态会发生改变,所以也就无法追踪了
如果我们需要异步操作,Mutations就不能满足我们需求了,这时候我们就需要Actions了
mutations: {
someMutation (state) {
api.callAsyncMethod(() => {
state.count++
})
}
}
4.4 actions
数据的异步(async)操作
五、案例
1. 同步与异步
首先我们state.js中设置我们要用的属性
state.js
export default{
resName:'多草率,除了你都不爱'
}
然后我们在getters.js中定义取值方法
getters.js
export default{
//拿值
getResName:(state)=>{
return state.resName;
}
}
然后定义mutations.js中定义同步修改方法
mutations.js
export default{
//同步修改值
setRessName:(state,payload)=>{
//satte对象对应了state.js中的变量对象
//payload 载荷对应的 传递的 json对象传递的参数{name:zs,age:12}
state.resName=payload.resName;
}
}
在actions.js中定义异步修改方法
actions.js
export default {
//异步修改值方法
setRessNameAsync: (context, payload) => {
//content指的是Vue的上下文,相当于this.$store
//休眠方法 此代码6秒后执行
setTimeout(function(){
context.commit("setRessName",payload);
},6000);
}
}
最后定义组件VuexPage1.vue和VuexPage2.vue,先在router下的index.js中配置
index.js
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from "@/components/HelloWorld";
import AppMain from "@/components/AppMain";
import LeftNav from "@/components/LeftNav";
import TopNav from "@/components/TopNav";
import Login from "@/views/Login";
import Reg from "@/views/Reg";
import Articles from "@/views/sys/Articles";
import VuexPage1 from '@/views/sys/VuexPage1';
import VuexPage2 from '@/views/sys/VuexPage2'
Vue.use(Router)
export default new Router({
routes: [{
path: '/',
name: 'Login',
component: Login
},
{
path: '/Login',
name: 'Login',
component: Login
},
{
path: '/Reg',
name: 'Reg',
component: Reg
},
{
path: '/AppMain',
name: 'AppMain',
component: AppMain,
children: [{
path: '/LeftNav',
name: 'LeftNav',
component: LeftNav
},
{
path: '/TopNav',
name: 'TopNav',
component: TopNav
},
{
path: '/sys/Articles',
name: 'Articles',
component: Articles
},
{
path: '/sys/VuexPage1',
name: 'VuexPage1',
component: VuexPage1
},
{
path: '/sys/VuexPage2',
name: 'VuexPage2',
component: VuexPage2
}
]
}
]
})
VuexPage1
<template>
<div>
<p>[页面1]猜歌名:{
{msg}}</p>
<button @click="bus">同步</button>
<button @click="busAsync">异步</button>
</div>
</template>
<script>
export default {
name:'VuexPage1',
data() {
return {
};
},
computed:{
msg(){
// 从vuex的state文件中获取值
//return this.$store.state.resName; //这种写法不推荐不安全
//通过getters.js文件获取state.js中定义的变量值
return this.$store.getters.getResName;
// this.$router.push()
// this.$router.Bus.$on()
}
},
methods:{
bus(){
//触发事件 通过commit方法会调用mutatuions.js文件中调用好的方法
this.$store.commit("setRessName",{
resName:'别自己和自己过不去'
});
},
busAsync(){
this.$store.dispatch("setRessNameAsync",{
resName:'别坦白 别让故事精彩',
})
}
}
}
</script>
<style>
</style>
VuexPage2
<template>
<div>
<p>【页面2】别继续 别比喻 别治愈{
{msg}}</p>
</div>
</template>
<script>
export default {
name:'VuexPage2',
data() {
return {
};
},
computed:{
msg(){
// 从vuex的state文件中获取值
//通过getters.js文件获取state.js中定义的变量值
return this.$store.getters.getResName;
}
}
}
</script>
<style>
</style>
效果
异步方法是设置了6秒后执行
当我们先点击异步,在点击同步时,就会出现,页面6秒前是别自己和自己过不去,而六秒后,我们的页面就会改成别坦白 别让故事精彩
2. 后台交互
我们如果想利用vuex进行后台交互,唯一要注意的点就是this的指向对象;
我们在actions.js中添加向后台请求菜单数据,那么当前页面里面的this指的是actions.js
而我们要用的是vue组件实例,所有我们通过参数把vue实例传递到action.js文件中使用
actions.js
export default {
//异步修改值方法
setRessNameAsync: (context, payload) => {
//content指的是Vue的上下文,相当于this.$store
//休眠方法 此代码6秒后执行
setTimeout(function(){
context.commit("setRessName",payload);
},6000);
let _this = payload._this;
//请求后台
let url = _this.axios.urls.SYSTEM_MENU_TREE;
_this.axios.post(url,{}).then(r=>{
console.log(r);
}).catch(e=>{
});
}
}
VuexPage1.vue
<template>
<div>
<p>[页面1]别犹豫 除了你都不爱{
{msg}}</p>
<button @click="bus">同步</button>
<button @click="busAsync">异步</button>
</div>
</template>
<script>
export default {
name:'VuexPage1',
data() {
return {
};
},
computed:{
msg(){
// 从vuex的state文件中获取值
//return this.$store.state.resName; //这种写法不推荐不安全
//通过getters.js文件获取state.js中定义的变量值
return this.$store.getters.getResName;
// this.$router.push()
// this.$router.Bus.$on()
}
},
methods:{
bus(){
//触发事件 通过commit方法会调用mutatuions.js文件中调用好的方法
this.$store.commit("setRessName",{
resName:'别自己和自己过不去'
});
},
busAsync(){
this.$store.dispatch("setRessNameAsync",{
resName:'别坦白 别让故事精彩',
_this:this
})
}
}
}
</script>
<style>
</style>
效果
当我们点击异步时,就可以接收到后台数据
今天的知识分享就到这里了!咱们有空再见!