javascript - vue中的箭头函数

标签 javascript vue.js

我在 vue 中的两个组件之间共享信息。在这一刻,我可以使用箭头函数获取创建的钩子(Hook)的值,但是,我不能将此值用于我声明的其他属性。我读到箭头函数在创建的钩子(Hook)中不起作用,我想知道如何替换这个箭头函数并获得我需要的值。

    data() {
        return{
        userloged:'',
        }
    },
    created(){
        serverBus.$on('validation', (user) =>{
            this.userloged = user
            console.log("Changed userloged", this.userloged)
            console.log("Here is the user", user) 
            return this.userloged})
    },

userloged 是我声明的属性。

最佳答案

来自 Vue's official docs :

Don’t use arrow functions on an options property or callback, such as created: () => console.log(this.a) [...]. Since arrow functions are bound to the parent context, this will not be the Vue instance as you’d expect, often resulting in errors such as Uncaught TypeError: Cannot read property of undefined.

很难看出如何在无法访问 minimal example that reproduces the issue 的情况下确保删除所有错误。 ,但是将 (user) => 替换为 function(user) 应该已经消除了主要错误。

关于javascript - vue中的箭头函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50280728/

相关文章:

javascript - Vue.js 在一个组件内的另一个组件中使用变量

javascript - 如何将参数传递给 Express post HTTP 方法?

javascript - Angular, restangular - 如果有更多当前的搜索调用,则中​​止搜索调用

vue.js - 如何在 Vue-cli3 中覆盖环境变量?

javascript - 为什么显式定义变量为未定义?

javascript - 使用 jquery 即时创建网格

vue.js - Vue Router Keep-Alive 包括不工作

javascript - Firebase 9 和 ref 函数与 Vue 组合

javascript - 克隆数组(不是引用副本)并修改新数组

javascript - 使用 setInterval 启动两个函数并让它们立即启动,没有延迟