目录:
1.Vue取值对比引出Vuex
2.Vuex简介
3.如何使用Vuex
4.具体代码
1.Vue取值对比引出Vuex
-
vue中各个组件之间传值
1.父子组件
父组件–>子组件,通过子组件的自定义属性:props
子组件–>父组件,通过自定义事件:this.$emit(‘事件名’,参数1,参数2,…);2.非父子组件或父子组件
通过数据总数Bus,this. r o o t . root. root.emit(‘事件名’,参数1,参数2,…)3.非父子组件或父子组件
更好的方式是在vue中使用vuex方法1: 用组件之间通讯。这样写很麻烦,并且写着写着,估计自己都不知道这是啥了,很容易写晕。
方法2: 我们定义全局变量。模块a的数据赋值给全局变量x。然后模块b获取x。这样我们就很容易获取到数据
但是方法2如果我们的子组件比较多的话,就变得比较麻烦,可能最后连自己都不记得自己定义的啥了。
因此,本节引出Vuex这一概念!
2.Vuex简介
官方解释:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。可以想象为一个“前端数据库”(数据仓库), 让其在各个页面上实现数据的共享包括状态,并且可操作
Vuex分成五个部分:
1.State:单一状态树
2.Getters:状态获取
3.Mutations:触发同步事件
4.Actions:提交mutation,可以包含异步操作
5.Module:将vuex进行分模块
3.如何使用Vuex
安装
npm install vuex -S
创建store模块,分别维护state/actions/mutations/getters
如图:
4.具体代码
在store/index.js文件中新建vuex的store实例,并注册上面引入的各大模块
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
每一个Vuex应用的核心就是store(仓库),store基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。
state, // 共同维护的一个状态,state里面可以是很多个全局状态
getters, // 获取数据并渲染
actions, // 数据的异步操作
mutations // 处理数据的唯一途径,state的改变或赋值只能在这里
在main.js中导入并使用store实例
// 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'
import 'element-ui/lib/theme-chalk/index.css'
//process.env.MOCK && require('@/mock')
import App from './App'
import router from './router'
import store from './store'
import ElementUI from 'element-ui'
import axios from '@/api/http'
import VueAxios from 'vue-axios'
Vue.use(ElementUI)
Vue.use(VueAxios,axios)
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
data(){
return {
Bus:new Vue({
})
}
},
router,
store,
components: { App },
template: '<App/>'
})
state(保存数据的容器)
export default {
resturantName: '飞歌餐馆'
}
this.$store.state.resturantName;//不建议
getters(getxx) 获取数据并渲染,
export default {
getResturantName: (state) => {
return state.resturantName;
}
}
mutations(setXxx) 处理数据的唯一途径,state的改变或赋值只能在这里
注1:mutations中方法的调用方式
不能直接调用this. s t o r e . m u t a t i o n s . s e t R e s t u r a n t N a m e ( ′ K F C ′ ) , 必 须 使 用 如 下 方 式 调 用 : t h i s . store.mutations.setResturantName('KFC'),必须使用如下方式调用: this. store.mutations.setResturantName(′KFC′),必须使用如下方式调用:this.store.commit(type,payload);
一定要记住,Mutation 必须是同步函数。为什么呢?异步方法,我们不知道什么时候状态会发生改变,所以也就无法追踪了 如果我们需要异步操作,Mutations就不能满足我们需求了,这时候我们就需要Actions了
export default {
setResturantName: (state, payload) => {
state.resturantName = payload.resturantName;
}
}
actions数据的异步(async)操作
export default {
setResturantNameAsync: (context, payload) => {
console.log('xxxx')
setTimeout(() => {
console.log('yyyy')
context.commit('setResturantName', payload); //Action提交的是mutation
}, 3000);
console.log('zzzz')
},
//vuex是不能使用Vue实例的
doAjax: (context, payload) => {
let _this = payload._this;
let url = _this.axios.urls.SYSTEM_USER_DOLOGIN;
console.log(url)
_this.axios.post(url, {})
.then((response) => {
console.log('doAjax..........')
console.log(response);
}).catch((response) => {
console.log(response);
});
}
}
Action类似于 mutation,不同在于:
1.Action提交的是mutation,而不是直接变更状态
2.Action可以包含任意异步操作
3.Action的回调函数接收一个 context 上下文参数,注意,这个参数可不一般,它与 store 实例有着相同的方法和属性
但是他们并不是同一个实例,context 包含:
1. state、2. rootState、3. getters、4. mutations、5. actions 五个属性
所以在这里可以使用 context.commit 来提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。
VuexPage1
<template>
<div>
<h3 style="margin: 60px;">第一个Vuex页面:{{title}}</h3>
<button @click="changeTitle">餐馆易主</button>
<button @click="changeTitleAsync">两个月后餐馆易主</button>
<button @click="doAjax">测试Vuex使用ajax</button>
</div>
</template>
<script>
export default {
data() {
return {
};
},
methods: {
changeTitle() {
this.$store.commit('setResturantName', {
resturantName: '小李菜刀牛肉馆'
});
},
changeTitleAsync() {
this.$store.dispatch('setResturantNameAsync', {
resturantName: '小李菜刀羊肉馆'
});
},
doAjax() {
this.$store.dispatch('setResturantNameAsync', {
_this:this
});
}
},
computed: {
title() {
/* return this.$store.state.resturantName; */
return this.$store.getters.getResturantName;
}
}
}
</script>
<style>
</style>
VuexPage2
<template>
<div>
<h3 style="margin: 60px;">第二个Vuex页面:{{title}}</h3>
</div>
</template>
<script>
export default {
data() {
return {
title: ''
};
},
created() {
this.title = this.$store.state.resturantName;
}
}
</script>
<style>
</style>
~~
5.测试效果: 如图