我想在页面加载时使用vue-resource
加载一些数据,然后在按下刷新按钮时重新加载该数据。
要保留我的代码DRY,我想将此功能放在方法中。这是我的第一次尝试:
的index.html:
<div id="app"></div>
app.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
中定义的任何方法?
答案 0 :(得分:9)
您应该通过以下方式使用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://vuejs.org/v2/api/#mounted
答案 1 :(得分:1)
您需要使用v-on(@)指令来侦听DOM事件,例如单击并以这种方式在方法中运行某些函数:
<button @click="loadData">Reload</button>
@Thusitha对于已安装是正确的,您需要更新它。