鍍金池/ 問(wèn)答/HTML/ vue + axios得到數(shù)據(jù)無(wú)法綁定到vue內(nèi) 詳細(xì)代碼如下

vue + axios得到數(shù)據(jù)無(wú)法綁定到vue內(nèi) 詳細(xì)代碼如下

======================
組件內(nèi)的代碼
============================

<script>
export default {
   data() {
         return{
         datas: [],
         }
   },
   created () {
     this.novelGet('http://novel.juhe.im/categories');
     console.log(this.datas);
   },
   methods: {
      // 路由跳轉(zhuǎn)執(zhí)行

   }
};
</script>


======================
引入了一個(gè)base.js novelGet 就是從里面得到的
============================


exports.install = function (Vue, options) {
    Vue.prototype.novelGet = function (url,dataName='data'){
        this.axios.get(url)
        .then((response)=> {
            // console.log(response.data);
            this.datas = response.data;
            console.log(this.datas);
        })
        .catch(function (error) {
            console.log(error);
        });
    };

我想要 axios 獲取到的數(shù)據(jù)賦予 datas 這個(gè)屬性內(nèi)。 我新手,不知道你們是怎么將數(shù)據(jù)應(yīng)用到組件內(nèi)(視圖)去的,如果有其他方法也可以,謝謝諸位援手!

回答
編輯回答
拽很帥

Vue組件中,data 聲明為返回一個(gè)初始數(shù)據(jù)對(duì)象的函數(shù),初始數(shù)據(jù)也就是這里的datas數(shù)組,不會(huì)被所有的實(shí)例共享引用,
所以在 base.js里面沒(méi)法獲取到組件中的datas數(shù)組,對(duì)應(yīng)的也沒(méi)法賦值。
這里的 this.datas = response.data;,只是為全局的Vue對(duì)象添加了一個(gè)datas屬性。
建議直接在組件里面引入axios,請(qǐng)求數(shù)組,并賦值給datas.

2018年1月7日 03:44
編輯回答
無(wú)標(biāo)題

在 novelGet 中已經(jīng)得到了數(shù)據(jù) 需要把數(shù)據(jù)return出來(lái) 不過(guò)很難想象你這一步axios封裝的用意是為何

2017年4月30日 14:24
編輯回答
乖乖瀦

樓上說(shuō)的對(duì),再提供兩個(gè)思路
一是使用狀態(tài)管理,把數(shù)據(jù)存到那里,也在那里取,二是在你的函數(shù)里提供一個(gè)回調(diào)函數(shù),在回調(diào)函數(shù)里賦值數(shù)據(jù)

2018年4月25日 05:30