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触发mutations2.你的.vue页面也需要修改,首先引入
import {mapState} from 'vuex'
,然后写成,用dispatch去派发action,这样<div>{{ channerlList }}</div>就能看到数据可以获取了。建议你加上watch监听 channerlList,如果不加只能直接把channerlList数据集合渲染到页面,如果要对channerlList数据在JS里进行其他处理首次是拿不到值的。例如: