请问vuex如何与axios结合在一起写?

modules下的channel.js

import axios from 'axios'
axios.defaults.baseURL = 'http://120.77.215.34:9001';

const state = {
  channelList:[],
};
const mutations = {
    GETCHANNELS(state,res){
      state.channelList=res;
    }
};

const actions = {
    getChannels({commit}){
      axios.get("/channel/guest",{withCredentials:true}).then(data=>{
        var res=data.data.myList;
        commit("GETCHANNELS",res)
      })
    }
};
export default{
  state,
  mutations,
  actions
}

store下的index.js

import Vue from 'vue'
import Vuex from 'Vuex'

import channel from './modules/channel'
import details from './modules/details'
import list from './modules/list'


Vue.use(Vuex);

export default new Vuex.Store({
  modules:{
    channel,
    details,
    list
  }
})

main.js

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'

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

hello.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h2>Essential Links</h2>
    <ul>
      <li v-for="(item,index) in this.$store.state.channel.channelList" :key="index">{{ item.name }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'hello',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  computed:{
     channerlList(){
      return this.$store.dispatch("getChannels")
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
</style>

想请问一下大家,vuex如何和axios结合在一起写,我这样写的没有报错,但是页面的li元素不会获取到数据,接口也没有进行请求,vue新手, 跪求大神指教!

刚刚大家说没有写派发,现在加了派发,如果加在computed里,没有报错,但是数据接口没有请求,也没有显示,如果写在mounted里,会报如下错误:

clipboard.png

阅读 6.6k
评论
    5 个回答
    • 307
      相似问题
      推荐文章