在写vue+vuex+axios请求数据之前,我们需要了解下什么是Vuex。
**
Vuex
**
vuex是一个集中式的存储仓库【状态】,类似于 本地存储、数据库,vuex是vue的状态管理工具,它的功能主要是实现多组件间的状态和数据共享
vuex的组成部分(其中state,action和mutation是它的核心组成)
- state: 状态
- action: 动作(业务交互)
- mutation: 修改state
- getter: 获取数据的
- store: state的存储者
应用实例
要使用Vuex必须先安装;
npm install vuex --save -dev
在store文件中生成index.js 文件和要管理的组件。
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import home from './home/index.js'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
home
}
})
export default store
home/index.js
import state from './state'
import actions from './actions'
import mutations from './mutations'
import getters from './getters'
const Home = {
state,
actions,
mutations,
getters
}
export default Home
home/actions.js
import axios from 'axios'
import * as type from './type'
// import { GET_NOW_HOT_MOVIES } from './type'
const actions = {
getHome ( { commit }) {
axios({
url: '/ajax/home/index',
method: 'GET',
params: {
token: ''
}
})
.then ( res => {
const action = {
type: type.GET_Home,
payload: res.data
}
commit( action )
})
.catch( error => {
if ( error ) throw error
})
}
}
export default actions
home/getters.js
const getters = {
new_Home(state){
return state.Home
}
}
export default getters
home/mutations.js
import * as type from './type'
const mutations = {
[type.GET_Home](state,action){
state.Home=action.payload
}
}
export default mutations
home/state.js
const state = {
Home:null,
}
export default state
home/type.js
扫描二维码关注公众号,回复:
12920618 查看本文章
export const GET_Home = 'GET_Home'
在项目的入口js文件main.js中
import store from ‘./store/index’
并将store挂载到vue上
这样我们就请求到后台的数据,让我们接下来在组件中直接使用他们。
在组建中我们需要引入mapActions, mapGetters
import { mapActions, mapGetters } from "vuex";
这样我们就将数据挂载在当前组件上了。
methods: {
...mapActions(["getHome"])
},
computed: {
...mapGetters(["new_Home"]),
resource() {
return this.new_Home && this.new_Home.result;
}
},
created() {
this.getHome();
this.resource = this.new_Home && this.new_Home.result;
}