安裝
npm install vuex --save
配置
- 在src中創(chuàng)建store 文件夾
- store創(chuàng)建 index.js
- 引入vue
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
home: 0,
},
actions: {
},
mutations: {
setHome (state, obj) {
state.home = obj.home
},
},
getters: {
home(state) {
return state.home
},
},
})
export default store
4.在main.js中引入vueX
import store from './store'
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})
使用
獲取store中的數(shù)據(jù)
1.在vue文件中引入vue
import {mapGetters} from 'vuex'
export default {
computed: {
...mapGetters({
home: 'home'
})
}
修改store中的數(shù)據(jù)
this.$store.state.home = 4
或者
this.$store.commit("setHome",4)
注意事項(xiàng)
IE兼容問題
在ie瀏覽器上報(bào)錯(cuò)
[vuex] vuex requires a Promise polyfill in this browser.
報(bào)錯(cuò)原因
IE瀏覽器沒有內(nèi)置的Promise對象轧抗,而且ES6新增語法在IE上也不能使用碘耳,比如Array.from攻走,因?yàn)閎abel只會(huì)轉(zhuǎn)譯語法晚缩,新語法無法轉(zhuǎn)義耕肩。
解決辦法
1.安裝babel-polyfill
npm install --save-dev babel-polyfill
2.修改配置webpack.base.config.js
entry: {
app: ['babel-polyfill','./src/main.js']
},