store.js中使用axios以及promise中对象的获取

在开发中,vuex里的state的数据是通过axios请求来的。

store.js中要使用axios就要先引入,然后直接使用axios, 

准备两个变量a和b,一个用来接收res的值,一个用来接收整个axios方法的值

store.js

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)
var a = [];
var b = axios.get("http://jsonplaceholder.typicode.com/posts").then(res=>{
    console.log(res);
     a = res.data
     return a;
})
export const store = new Vuex.Store({
    state:{
        prod :b
    }
})

现在可以获取state中的值了,在created生命周期中,使用this.$store.state.prod获取。

通过axios请求来的state的值,是个promise对象

promise对象的值的内容,可以通过then(res=>{})方法获取

  data () {
    return {
       c:[]
    };
  },

  created(){
   var getValue =  this.$store.state.prod; //这里获得的值是个promise对象
  //通过then方法获取promise对象 getValue.then(res
=>{ console.log(res); //获得state里的数据,把数据赋值给data里的变量 this.c = res; }) }

猜你喜欢

转载自www.cnblogs.com/luguankun/p/10842327.html