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

查看:100
本文介绍了javascript - 请问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里,会报如下错误:

解决方案

有两个地方需要修改:1.channel.js下action里面不能直接赋值,这么写var res=data.data.myList是不对的,应该写成commit('GETCHANNELS', res),使用commit触发mutations
2.你的.vue页面也需要修改,首先引入import {mapState} from 'vuex',然后写成,用dispatch去派发action,这样<div>{{ channerlList }}</div>就能看到数据可以获取了。

computed: {
      ...mapState({
        channerlList: state => state.channel.channelList
      })
    },
    mounted () {
      this.$store.dispatch('getChannels')
    }

建议你加上watch监听 channerlList,如果不加只能直接把channerlList数据集合渲染到页面,如果要对channerlList数据在JS里进行其他处理首次是拿不到值的。例如:

watch: {
      channerlList (val) {
        this.lists = val
        console.log(this.lists)
      }
    }

这篇关于javascript - 请问vuex如何与axios结合在一起写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆