vuex传递数据
如果涉及到多种数据在父子、兄弟组件之间传递时,vuex是一个很好的方法。
首先来看怎么安装vuex
npm install vuex
然后在src里面会出现store文件夹,我们将数据写在这个index.js文件中
如何引用:
在main.js中 import store,在 new vue中添加store
import store from './store/index'
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
再来看vuex的四个部分:state, mutations,actions,getters.
举一个登录状态的例子,有两种状态:login和register
state用来存放静态数据
更改store中state值的唯一方法就是提交mutation,每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数
actions用来调用mutation
getters用来获取数据
const state={
loginway:'login',
}
const mutations={
CHANGE_LOGINWAY(state,type){
state.loginway=type
},
}
const actions={
//改变登录方式
changeLoginway({commit},type){
commit('CHANGE_LOGINWAY',type)
},
}
const getters={
getLoginway:function(state){
return state.loginway
},
}
如何在组件中使用
import {mapGetters} from 'vuex'
import store from '@/store'
//获取属性,调用的时候直接使用this.zoom就可以
computed: {
...mapGetters({
center:'getMapcenter',
zoom:'getzoom'
}),
//改变属性
this.$store.dispatch('changecenter',center);