import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'
Vue.use(Vuex)
export default new Vuex.Store({
// 存储数据
state,
// 修改方法
mutations
})
在main.js中引入并实例化
import store from '@/store/index'
new Vue({
el: '#app',
router,
// 实例化store
store,
render: h => h(App)
})
4.到这里vuex已经配置完成,只要在state.js中写入数据即可在项目中引用了
state.js
const state = {
//这里以常用的用户id为例,可以是任意你想保存的数据
userId: '0123456789'
}
export default state
5.现在你就可以在项目中的任何组件取到用户id,方法如下(关于map的作用就自己查阅资料吧)
import { mapState } from 'vuex'
export default {
computed: {
...mapState({
userId: state => state.userId
})
},
// 然后在你需要的地方使用this.userId即可,如
created () {
console.log(this.userId)
}
}