Vue实战:使用Vuex结合毕业设计实现数据共享
一、存在问题
预约功能中,需要显示预约充电桩的信息,这时候我已经调用的后台的API接口获取了充电桩信息,里面包含了经纬度,这时候路线功能也是需要用到充电桩的经纬度,如果两个都一直调用的话,不如弄成数据共享,当项目涉及大量数据进行传递的时候,可以利用vuex数据框架:https://vuex.vuejs.org/zh/
二、Vuex简单介绍
当我们项目多个组件进行复杂的传值的时候,就把公用数据放到公用存储空间,当一个组件改变数据,其他组件都可以感知到
Vuex虚线部分内容,就是公用数据存储区域,我们所有数据都存在state当中,组件修改数据时需要先调用action,action做一些异步处理,再去调用mutations才可以修改公用数据的值
三、原毕设项目
从3.1跟3.2可以看到,充电桩经纬度需要在information中传递给map中,那么将经纬度位置设置为共享数据
3.1 Reserve.vue中的Information
reach(){
this.$router.push({path:'/route/',
query:{chargeLongitude:this.chargeLongitude,
chargeLatitude:this.chargeLatitude}});
},
3.2 Route.vue中的Map
data(){
return{
chargeLongitude : this.$route.query.chargeLongitude,
chargeLatitude : this.$route.query.chargeLatitude,
...
四、修改毕设项目
4.1 安装
npm install vuex --save
4.2 创建单独文件夹
创建单独文件夹方便管理
4.3 index.js
由于vuex是一个插件,所有使用点use来使用,并创建vuex厂库
state:存储共享的数据
action:改变数据前调用,第一个参数为上下文,第二个参数为object,只能传递一个参数,传递多个参数的方法
mutation:改变共享的数据
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{
chargeLongitude:'',
chargeLatitude:'',
},
actions:{
getLongitude(ctx,chargeLongitude){
ctx.commit('getLongitude',chargeLongitude)
},
getLatitude(ctx,chargeLatitude){
ctx.commit('getLatitude',chargeLatitude)
}
},
mutations:{
//改变数据
getLongitude(state,chargeLongitude,){
state.chargeLongitude = chargeLongitude
},
getLatitude(state,chargeLatitude){
state.chargeLatitude = chargeLatitude
}
}
})
4.4 main.js中引入
在main.js中引入,创建vue根实例的时候把store传入进去
import store from './store/index'
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
4.5 Reserve.vue中的Information
调用action的时候看流程图可知使用dispatch方法
reach(){
//vuex调用action改变数据
this.$store.dispatch('getLongitude',this.chargeLongitude)
this.$store.dispatch('getLatitude',this.chargeLatitude)
this.$router.push({path:'/route/'});
},
4.6 Route.vue中的Map
data(){
return{
chargeLongitude : this.$store.state.chargeLongitude,
chargeLatitude : this.$store.state.chargeLatitude,
...