未在已安装的钩子中定义的方法,Vue JS

Posted

技术标签:

【中文标题】未在已安装的钩子中定义的方法,Vue JS【英文标题】:Method not defined in mounted hook, Vue JS 【发布时间】:2017-04-11 08:52:08 【问题描述】:

所以我正在使用 Laravel 5.3,我正在尝试创建一个 DataTable,我正在尝试创建一个从后端获取数据的方法,并且我试图在组件完成后立即调用它准备好了。

我发现 ready() 钩子现在已经失效并被 mount() 取代,因此我的模板看起来像这样。

<template>
..Simple Bootstrap table...
</template>

<script>
    export default 
        data: () => 
            return 
                searchQuery: "",
                columns: ['ID', 'Name', 'Campaign', 'Method', 'Limit Per Connection', 'Limit Per Day', 'Active', 'Last Ran'],
                lastId: 0,
                rowsPerPage: 10,
                gridData: [
                     id: 1, name: "Example 1", campaign: 3412, method: "POST", limitConn: 1250, limitDay: 50, active: "Yes", lastRun: "2016-11-27 18:42:21",
                     id: 2, name: "Example 1", campaign: 3412, method: "POST", limitConn: 1250, limitDay: 50, active: "Yes", lastRun: "2016-11-27 18:42:21",
                     id: 3, name: "Example 1", campaign: 3412, method: "POST", limitConn: 1250, limitDay: 50, active: "Yes", lastRun: "2016-11-27 18:42:21",
                     id: 4, name: "Example 1", campaign: 3412, method: "POST", limitConn: 1250, limitDay: 50, active: "Yes", lastRun: "2016-11-27 18:42:21",
                     id: 5, name: "Example 1", campaign: 3412, method: "POST", limitConn: 1250, limitDay: 50, active: "Yes", lastRun: "2016-11-27 18:42:21",
                     id: 6, name: "Example 1", campaign: 3412, method: "POST", limitConn: 1250, limitDay: 50, active: "Yes", lastRun: "2016-11-27 18:42:21",
                     id: 7, name: "Example 1", campaign: 3412, method: "POST", limitConn: 1250, limitDay: 50, active: "Yes", lastRun: "2016-11-27 18:42:21"
                ]
            
        ,
        methods: 
            /**
             * Fetch JSON data for crons from the Backend
             *
             * @param lastId - The last ID in the current data
             */
            fetchData: (lastId) => 
                Vue.http.get('/data').success((response) => 

                    console.log(response);

                ).error((response) => 

                    console.error(response);

                )
            ,
        ,
        mounted: () => 
            // When the Component is ready fetch the JSON from the Server Backend
            this.fetchData(0);
        ,
    
</script>

<style>...My Css...</style>

Mounted 方法触发但说this$1.fetchData is not defined 知道我做错了什么吗? Mounted 钩子是否无法访问我的方法?

【问题讨论】:

【参考方案1】:

mounted 的语法应如下所示:

mounted () 
    // When the Component is ready fetch the JSON from the Server Backend
    this.fetchData(0);
  

Don't use arrow function for lifecycle hooks,箭头函数使用由上下文确定的词法this,vue 将无法为我们绑定它。

【讨论】:

哇哦,原来如此,这不就是定义函数吗?这样做和使用 ES6 语法到底有什么区别?非常感谢:)

以上是关于未在已安装的钩子中定义的方法,Vue JS的主要内容,如果未能解决你的问题,请参考以下文章

Vue.js 无法更改其他钩子和方法中的数据

10个有用的自定义钩子vue.js

vue自定义指令钩子函数

反应上下文(钩子)不更新所有引用

vue生命周期注意事项

Vue生命周期内的钩子方法