VueJS语法:在Promise中保存一个值

问题描述:

使用some help from *当页面加载和单击按钮时,我得到以下内容来运行我的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

它看起来不像你有一个数据对象。只有数据对象中的属性是被动的。 –

您必须在组件数据中定义文本属性。

从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>