首先我们在入口 store/index.js 文件中,将 Vuex 挂载到 Vue 上
import Vue from 'vue'
import Vuex from 'vuex'
// 根级别
import actions from './actions'
// 页面级
import list from './modules/list'
import detail from './modules/detail'
// 功能模块级
import activity from './modules/activity'
import comment from './modules/comment'
Vue.use(Vuex)
const store = new Vuex.Store({
actions,
modules: {
list,
detail,
activity,
comment
}
})
export default store
请求方式一 (在独立的 js 文件中使用):
import store from '../store'
// 获取一个属性
const isWeChat = store.getters.isWeChat
// 请求一个方法
const getCommentList = (data, callback) => {
const params = {
userId: 0,
status: 0,
...data
}
store.dispatch('comment/fetchCommentList', {
params: params,
callback: res => {
// TODO: 获取到数据之后的请求操作
}
})
}
module.exports = {
isWeChat: isWeChat,
getCommentList: getCommentList
}
请求方式二:
this.$store
.dispatch('getServerTime')
.then(res => {
...
})
.catch(err => {
...
})
请求 modules 中的方法
this.$store
.dispatch('comment/fetchCommentList')
.then(res => {
...
})
.catch(err => {
...
})
请求方式三:
import { mapActions } from 'vuex'
...
methods: {
...mapActions('comment', ['fetchCommentList']),
getCommentList(postData) {
this.fetchCommentList(postData)
}
}
...
如果将数据推送到了 store.state 中,可以在 computed 中用下面方式接收:
computed: {
myCommentList() {
return this.$store.state.comment.myCommentList
}
}
整体调用示例:
<template>
...
</template>
<script>
import { mapActions } from 'vuex'
export default {
name: 'testPage',
data() {
return {
isWechat: false
}
},
created() {
this.init()
},
methods: {
...mapActions('comment', ['fetchCommentList']),
...mapActions('praise', ['fetchAddPraise']),
init() {
// TODO: 初始化请求数据
this.$store
.dispatch('getServerTime')
.then(res => {
this.$storage.set('time', new Date().getTime() - res)
...
})
.catch(err => {
console.warn('---getServerTime---', err)
})
},
getCommentList(postData) {
this.fetchCommentList(postData)
},
},
computed: {
myCommentList() {
return this.$store.state.comment.myCommentList
}
}
}
</script>
<style lang="less" scoped>
...
</style>
来源:oschina
链接:https://my.oschina.net/u/943746/blog/3130148