Vue组件中直接获取Vuex状态state数据

account.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
export default {
state: {
user: {
'data': null
'success': false,
'timestamp': 0
}
},
mutations: {
...
},
actions: {
...
}
}

在另一个组件中获取user数据

1
2
3
4
5
6
export default {
created () {
let user = this.$store.state.account.user.data
console.log(user)
},
}

注:使用$store的前提是在main.js中初始化Vue时加载store/index.js

main.js

1
2
3
4
5
6
7
8
9
10
11
12
13
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store/index.js'

/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})

store/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import Vue from 'vue'
import Vuex from 'vuex'
import * as getters from './getters'

import account from './modules/account'

Vue.use(Vuex)
const debug = process.env.NODE_ENV !== 'production'

export default new Vuex.Store({
getters,
modules: {
account
},
strict: debug
})

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :