想实现这样一个需求, 项目中有一个列表在多个页面中都使用到了, 不想每个页面都用 axios 请求一次数据, 所以想着用 vuex 来存储, 这样, 组件里面就可以直接拿来用了, 不用写许多重复的代码;
以下直接上代码:
首先要安装 vuex, NPM install --save vuex;
接下来是在 src 文件夹下新建 store/index, 代码内容:
- import Vue from 'vue'; // 首先引入 vue
- import Vuex from 'vuex'; // 引入 vuex
- import API from '../API/index' // 这里是因为封装了 axios 的方法在里面, 所以可以直接引用
- Vue.use(Vuex)
- export default new Vuex.Store({
- state: {
- domainList: []
- },
- mutations:{
- updateDomain (state, payload) {
- state.domainList = payload
- }
- },
- actions:{
- getAllDomain (context) {
- API.getStatList(true).then((response) => {
- let res = response.data;
- if (res.code == 0) {
- context.commit('updateDomain', res.data.items);
- }
- })
- }
- }
- })
接下来是在 main.JS 中引用
- import store from './store/index.JS'
- /* eslint-disable no-new */
- new Vue({
- el: '#App',
- router,
- store, // 加上 store
- components: { App },
- template: '<App/>'
- })
接下来是在需要使用到 domainList 这个数据的组件中去使用:
- export default {
- computed: {
- domainList () {
- return this.$store.state.domainList; // 获取 state 中的 domainList
- }
- },
- mounted () {
- this.$store.dispatch('getAllDomain'); // 直接调用 store/index.JS 中的方法
- }
- }
来源: http://www.qdfuns.com/note/46360/aa5fef406e8843e8b343f5fd5c384987.html