VueJS语法:在Promise中保存值

ste*_*esu 0 javascript vue.js vuejs2

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>
Run Code Online (Sandbox Code Playgroud)

小智 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
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)