2017-09-26 57 views
0

使用some help from StackOverflow當頁面加載和單擊按鈕時,我得到以下內容來運行我的loadDataVueJS語法:在Promise中保存一個值

但是,頁面上的文本沒有更新。我的語法有點不對this.text = xhr.data

index.html: 

<div id="app"></div> 

app.js: 

const Vue = window.Vue = require("vue"); 
Vue.prototype.$http = require("axios"); 
const App = require("./components/App.vue"); 

window.app = new Vue({ 
    el: "#app", 
    render: h => h(App) 
}); 

components/app.vue: 

<template> 
    <div> 
     <h1>Test</h1> 
     <p>{{text}}</p> 
     <button @click="this.loadData">Reload</button> 
    </div> 
</template> 
<script> 
export default { 
    mounted() { 
     this.loadData(); 
    }, 
    methods: { 
     loadData() { 
      this.$http.get("https://icanhazip.com") 
       // This fails 
       .then(xhr => this.text = xhr.data); 
     } 
    } 
}; 
</script> 
+0

任何錯誤訊息? –

+2

它看起來不像你有一個數據對象。只有數據對象中的屬性是被動的。 –

回答

5

您必須在組件數據中定義文本屬性。

從Vue.js文檔:

由於現代的JavaScript(和Object.observe的遺棄)的侷限性,Vue公司無法檢測屬性添加或刪除。由於Vue在實例初始化期間執行getter/setter轉換過程,因此數據對象中必須存在一個屬性,以便Vue將其轉換並使其處於被動狀態。例如:

var vm = new Vue({ 
    data: { 
    a: 1 
    } 
}) 
// `vm.a` is now reactive 
vm.b = 2 
// `vm.b` is NOT reactive 

在你的情況你的組件應該是這樣的:

<script> 
export default { 
    created() { 
     this.loadData(); 
    }, 
    data() { 
     return { 
      text: '', 
     }; 
    }, 
    methods: { 
     loadData() { 
      this.$http.get("https://icanhazip.com") 
       // This fails 
       .then(xhr => this.text = xhr.data); 
     } 
    } 
}; 
</script>