在開發中,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; }) }