我在Vue.js中使用Typescript编写了这个,我无法弄清楚为什么错误变量在startLogin()中被更改后变为undefined.我之前尝试过直接在startLogin()中更改字符串,但它仍然保持不变.感谢任何帮助,我花了好几个小时盯着这个.如果我在startLogin()中执行console.log,则错误变量具有正确的值,但是当我在其他地方使用它时,它是未定义的.
<script lang="ts">
import App from "./App.vue";
import router from "./router";
import store from "./store";
import "./registerServiceWorker";
import { Component, Prop, Vue } from "vue-property-decorator";
@Component
export default class Login extends Vue {
error: number;
username: string;
password: string;
constructor(){
super();
this.error = 0;
this.username ="";
this.password ="";
}
startLogin(): void {
if(this.$data.username != "" && this.$data.password != "") {
if(this.$data.username == "michaela") {
this.$emit("authenticated", true);
new Vue({
router,
store,
render: h => h(App)
}).$mount("#login");
} else {
this.$data.error = 1;
}
} else {
this.$data.error = 2;
}
}
get errorMsg() {
console.log(this.$data.error);
if(this.$data.error == 0){
return "Please enter your username and password";
} else if(this.$data.error == 1){
return "The username or password is incorrect";
} else if(this.$data.error == 2){
return "Both username and password must be present";
}
}
}
</script>
<style lang="scss">
#login {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
h1 {
font-size: 30px;
padding: 0;
}
form {
color: #2c3e50;
color: white;
padding: 0;
margin: auto;
width: 300px;
}
form h1 {
margin: auto;
color: #2c3e50;
}
input, select, textarea {
display: inline-block;
width: 70%;
padding: 16px 20px 10px 10px;
border: none;
background-color: lightseagreen;
color: white;
margin: auto;
}
input {
height: 10px;
font-size: 15px;
}
textarea {
height: 30px;
}
label, form p {
display: block;
margin: 10px 0px 0px 0px;
}
form .button, button {
height: 30px;
width: 80px;
text-align: center;
padding: 0;
background-color: lightseagreen;
border: none;
color: white;
margin: auto;
}
::placeholder {
color: white;
}
.error {
color: red;
}
</style>
<template>
<div id="login">
<h1>Login</h1>
<p :class="{'error' : error != 0}">{{errorMsg}}</p>
<form>
<p><input type="text" name="username" v-model="username" placeholder="Username" /></p>
<p><input type="password" name="password" v-model="password" placeholder="Password" /></p>
<p><button type="button" v-on:click="error = startLogin()">Submit</button></p>
</form>
</div>
</template>
最佳答案 你写下面的内容:
<button type="button" v-on:click="error = startLogin()">Submit</button></p>
所以基本上你期望函数startLogin()返回一个数字值.
但是,在当前的实现中,startLogin()没有返回值(即:startLogin():void).
为了定义错误变量,您应该使startLogin()返回错误值或避免执行error = startLogin()赋值.