javascript - VueJS 语法 : Running method on mount

标签 javascript vue.js vuejs2

我想在页面加载时使用 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/

相关文章:

vue.js - 我怎样才能删除 __ob__ : Observer from my array list?

javascript - initMap 不是 Google Maps Javascript 的函数

javascript - Bootstrap 选项卡在 Vue 应用程序中不起作用

javascript - 如何在vue.js中解析json?

javascript - 使用 Vuejs 中的 Api 响应映射 Json 文件

javascript - 如何用vue监听html标签的onload事件?

javascript - 可拖动的 jQuery 轮播定制

javascript - Vue3 通过 Router View 将 props 传递给组件渲染

javascript - 使用 minicart.js 显示购物车中的商品数量

javascript - Storybook 中的 Vuex 存储未定义