VueJS语法:mount上的运行方法

ste*_*esu 5 javascript vue.js vuejs2

我想vue-resource在页面加载时加载一些数据,然后在按下刷新按钮时重新加载该数据.

为了保持我的代码干,我想把这个功能放在一个方法中.这是我的第一次尝试:

index.html的:

<div id="app"></div>
Run Code Online (Sandbox Code Playgroud)

组件/ app.vue:

const Vue = window.Vue = require("vue");
require("vue-resource");
const App = require("./components/App.vue");

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

这会在第10行引发错误components/app.vue:

<template>
    <div>
        <h1>Test</h1>
        <p>{text}</p>
        <button @click="loadData">Reload</button>
    </div>
</template>
<script>
export default {
    // This fails
    mounted: this.loadData,
    methods: {
        loadData() {
            // This syntax may be wrong, too. But the function isn't
            // even running, so I haven't started to debug this yet
            this.$http.get("https://icanhazip.com")
                .then(xhr => this.text = xhr.body);
        }
    }
};
</script>
Run Code Online (Sandbox Code Playgroud)

Uncaught TypeError: Cannot read property 'reloadData' of undefined

如何让mounted函数引用中定义的任何方法methods

Thu*_*tha 11

您应该使用mounted以下方式使用事件并使用正确的方法声明.

export default {        
    mounted() {
      this.loadData();
    },
    methods: {
        loadData() {
            // This syntax may be wrong, too. But the function isn't
            // even running, so I haven't started to debug this yet
            this.$http.get("https://icanhazip.com")
                .then(xhr => this.text = xhr.body);
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

更多详细信息可以在这里找到.
https://vuejs.org/v2/api/#mounted