VueJS 语法:挂载上的运行方法 [英] VueJS Syntax: Running method on mount
问题描述
我想在页面加载时使用 vue-resource
加载一些数据,然后在按下刷新按钮时重新加载该数据.
为了保持我的代码DRY,我想将此功能放在一个方法中.这是我的第一次尝试:
index.html:
app.js:
const Vue = window.Vue = require("vue");require("vue-资源");const App = require("./components/App.vue");window.app = 新的 Vue({el: "#app",渲染:h =>h(应用程序)});
components/app.vue:
<div><h1>测试</h1><p>{text}</p><button @click="loadData">重新加载</button>
</模板><脚本>导出默认{//失败安装:this.loadData,方法: {加载数据(){//这种语法也可能是错误的.但功能不是//甚至运行,所以我还没有开始调试this.$http.get("https://icanhazip.com").then(xhr => this.text = xhr.body);}}};
这会在 components/app.vue
的第 10 行抛出错误:
挂载:this.loadData,
说未捕获的类型错误:无法读取未定义的属性reloadData"
如何让 mounted
函数引用 methods
中定义的任何方法?
你应该按照以下方式使用 mounted
事件并正确声明方法.
出口默认{安装(){this.loadData();},方法: {加载数据(){//这种语法也可能是错误的.但功能不是//甚至运行,所以我还没有开始调试this.$http.get("https://icanhazip.com").then(xhr => this.text = xhr.body);}}};
可以在此处找到更多详细信息.
https://vuejs.org/v2/api/#mounted
I would like to load some data with vue-resource
when a page loads, then re-load that data if a refresh button is pressed.
To keep my code DRY I wanted to put this functionality in a method. This was my first attempt:
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)
});
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>
This throws an error on line 10 of components/app.vue
:
mounted: this.loadData,
Saying Uncaught TypeError: Cannot read property 'reloadData' of undefined
How can I get the mounted
function to refer to any of the methods defined in methods
?
You should use mounted
event in following way with correct method declaration.
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);
}
}
};
More details can be found here.
https://vuejs.org/v2/api/#mounted
这篇关于VueJS 语法:挂载上的运行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!