vuex簡單搭建使用

安裝

npm install vuex --save

配置

  1. 在src中創建store 文件夾
  2. store創建 index.js
  3. 引入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中的數據

1.在vue文件中引入vue

import {mapGetters} from 'vuex'
export default {
    
computed: {
...mapGetters({
    home: 'home'
})
}

修改store中的數據

this.$store.state.home = 4

或者

this.$store.commit("setHome",4)

注意事項

IE兼容問題

在ie瀏覽器上報錯

[vuex] vuex requires a Promise polyfill in this browser.

報錯原因

IE瀏覽器沒有內置的Promise對象,而且ES6新增語法在IE上也不能使用,比如Array.from,因為babel只會轉譯語法,新語法無法轉義。

解決辦法

1.安裝babel-polyfill

npm install --save-dev babel-polyfill

2.修改配置webpack.base.config.js

entry: {
app: ['babel-polyfill','./src/main.js']
},
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容