gpt4 book ai didi

javascript - 如何在 .addEventListener 中访问 Vue.prototype?

转载 作者:行者123 更新时间:2023-12-04 13:29:07 27 4
gpt4 key购买 nike

我正在尝试访问 Vue.prototype.$firebase 的全局对象在 main.js 中声明

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import VueTailwind from "vue-tailwind";
import { FirebaseApp } from "@/firebase/firebase";
//Style
import "@/assets/styles/app.css";
import settings from "@/assets/styles/Tailwind.js";

FirebaseApp.auth().onAuthStateChanged((user)=>{
Vue.prototype.$user = user;
})

//Vue
Vue.config.productionTip = false;
Vue.use(VueTailwind, settings);
Vue.prototype.$firebase = FirebaseApp;

new Vue({
router,
render: h => h(App)
}).$mount("#app");
内部 Login成分
<script>
export default {
name: "Login",
mounted: function () {
this.submit();
},
methods: {
submit() {
let login = document.getElementById("login");
login.addEventListener(
"submit",
function (event) {
event.preventDefault();
const email = login.email.value;
const password = login.password.value;
this.$firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then((user) => {
console.log(user)
this.$router.replace('/')
})
.catch((error) => {
console.log(error);
});
},
true
);
},
},
};
</script>
但我得到 TypeError: Cannot read property 'auth' of undefined ,同 this.$router .
但是在 .addEvenListener之外实例化对象打印效果很好,让我可以通过 let signIn 访问,但这不是我想要的行为,相反,我想在 login 之间“自动”路由和一个 dashboardonAuthStateChange通过使用 Vue.prototype.$firebase 而不是本地实例化进行登录:
<script>
export default {
name: "Login",
mounted: function () {
this.submit();
},
methods: {
submit() {
let login = document.getElementById("login");
let signIn = this.$FirebaseApp;
let onLogin = this.$router;
login.addEventListener(
"submit",
function (event) {
event.preventDefault();
const email = login.email.value;
const password = login.password.value;
signIn
.auth()
.signInWithEmailAndPassword(email, password)
.then((user) => {
console.log(user)
onLogin.replace('/')
})
.catch((error) => {
console.log(error);
});
},
true
);
},
},
};
</script>
访问 Vue.prototype.$firebase的正确方法是什么?为什么它有这样的范围限制?

最佳答案

避免使用 function()内部组件回调并使用 arrow functions反而。function创建自己的 this上下文,以便 this将不再引用组件,但箭头函数使用周围的 this语境:

login.addEventListener(
"submit",
(event) => { // Changed to arrow function
... // Now you can access `this.$firebase`
},
true
);

关于javascript - 如何在 .addEventListener 中访问 Vue.prototype?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66282275/

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