第一步:頁面發(fā)送axios請求
created() {
// 請求數(shù)據(jù)
axios
.get("https://cnodejs.org/api/v1/topics", {
// 請求體`
params: {
page: "1",
limit: "40",
},
})
.then((res) => {
let _this = this;
// 把數(shù)據(jù)傳到vuex里面
_this.$store.commit("setData", res.data.data); //res.data.data 為請求返回的數(shù)據(jù)
});
},
第二步:vuex里面接收數(shù)據(jù)
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
// 創(chuàng)建新一個數(shù)組存入請求到到數(shù)據(jù)
arr:[]
},
// 唯一修改state屬性的方法
mutations: {
setData(state,payload){
state.arr=payload
//這里打印下看下是否有接收到,
console.log(state.arr);
}
},
actions: {
},
modules: {
}
})
第三步:在組件中按需引入
<template>
<div>
<div>{{arr}}</div>
</div>
</template>
<script>
// 按需引入vuex
import {mapState} from "vuex"
export default {
computed:{
// 到這一步就獲取到數(shù)據(jù)了
...mapState(['arr'])
}
}
</script>
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者