我想在页面加载时使用 vue-resource
加载一些数据,然后在按下刷新按钮时重新加载该数据。
保留我的代码 DRY我想把这个功能放在一个方法中。这是我的第一次尝试:
index.html:
<div id="app"></div>
应用程序.js:
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)
});
组件/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>
这会在 components/app.vue
的第 10 行引发错误:
mounted: this.loadData,
说 Uncaught TypeError: Cannot read property 'reloadData' of undefined
如何让 mounted
函数引用 methods
中定义的任何方法?
最佳答案
您应该按照以下方式使用 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);
}
}
};
可以在此处找到更多详细信息。
https://v2.vuejs.org/v2/api/#mounted
关于javascript - VueJS 语法 : Running method on mount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46427612/