VueJS语法:安装时的运行方法

VueJS语法:安装时的运行方法

问题描述:

我想在页面加载时加载vue-resource的一些数据,然后在按下刷新按钮时重新加载该数据。VueJS语法:安装时的运行方法

为了保持我的代码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中定义的任何方法?

+1

顺便说一句:'vue-resource'已经不是什么了。 https://medium.com/the-vue-point/retiring-vue-resource-871a82880af4 – sandrooco

您应该使用正确的方法声明以下列方式使用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

您需要使用V-上(@)指令来听像点击DOM事件,并运行在以这种方式方法的一些功能:

<button @click="loadData">Reload</button> 

@Thusitha是安装正确,你需要更新它。

+0

+1因为这指出了一个有效的问题,但不能接受,因为它实际上并没有回答原来的问题。 – stevendesu