gpt4 book ai didi

javascript - Vue.js 数据在 created() 函数中不可用

转载 作者:搜寻专家 更新时间:2023-10-30 22:39:09 25 4
gpt4 key购买 nike

我在使用 localStorage 中的数据初始化我的 Vue 组件时遇到问题。这是我的代码的简化版本

new Vue({
el: "#my-element",
created: () => {
if (window.localStorage.getItem("verified")) {
this.verification.verified = true;
}
},
data: {
verification: {
verified: false
}
}
});

但我一直在控制台上收到错误 Cannot read property 'verification' of undefined

如果我在 created() 函数中放置一个 debugger,然后检查 thisthis.verificationthis.verification.verified,它们都设置为我在数据对象中初始化的值。

谁能解释一下我做错了什么?

基本上,如果用户之前已经完成了验证过程,我会尝试在页面加载时隐藏一个元素。

最佳答案

当您需要 this 的值时,可以使用箭头函数。在外部上下文中流入你的函数体,而不是函数有自己的 this 上下文.这意味着 this在你的created函数没有指向你的 Vue 实例。

但是您仍然可以使用 ES6 提供的简写方法声明语法:

new Vue({
created() {
// ...
}
});

关于javascript - Vue.js 数据在 created() 函数中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42149800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com