VueJS语法:在Promise中保存值

时间:2017-09-26 14:10:13

标签: javascript vue.js vuejs2

使用some help from StackOverflow我在页面加载和点击按钮时运行loadData以下内容。

但是页面上的文字没有更新。我使用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>

1 个答案:

答案 0 :(得分:5)

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

来自Vue.js文档:

由于现代JavaScript的限制(以及放弃Object.observe),Vue无法检测属性添加或删除。由于Vue在实例初始化期间执行getter / setter转换过程,因此数据对象中必须存在一个属性,以便Vue转换它并使其具有反应性。例如:

org.eclipse.birt.runtime_4.6.0-20160607.jar

在您的情况下,您的组件应如下所示:

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