【发布时间】:2021-04-20 12:17:33
【问题描述】:
我正在学习 Vue,希望能得到帮助,因为我在这里或互联网的其他地方找不到关于为什么我的单选按钮无法使用 v-if 语句的答案,即使我已经绑定了模型我可以看到值的变化。
预期结果:
如果用户使用单选按钮切换他们是否有学位,如果他们选择 false,则具有“degree-wrapper”类的 div 将消失。
实际结果:
用户使用单选按钮切换是否有学位,如果他们选择 false,则具有“degree-wrapper”类的 div 不会消失。
我觉得奇怪的是我可以看到值的变化并且值是绑定的?那么为什么当 v-model 将其更改为 false 时,v-if 切换不显示“degree-wrapper”div。
这是我用 vue3 和 typescript 中的类编写的代码。
<template>
<div class="page-wrapper">
<div class="user-data-wrapper">
<h3>Users Data</h3>
<p>first name: {{ userData.firstName }}</p>
<p>last name: {{ userData.secondName }}</p>
<p>age: {{ userData.age }}</p>
<p>location: {{ userData.location }}</p>
<p>date of birth: {{ userData.dateOfBirth }}</p>
<p>has a degree?: {{ userData.hasDegree }}</p>
</div>
<div class="user-update-wrapper">
<h3>Update your user info</h3>
<label for="full-name">Fullname: </label><br>
<input type="text" id="full-name" name="full-name" v-model="fullName"><br>
<label for="full-name">Do you have a degree?: </label><br>
<input type="radio" v-model="userData.hasDegree" value="false">false<br>
<input type="radio" v-model="userData.hasDegree" value="true">true<br>
<div v-if="userData.hasDegree" class="degree-wrapper">
<label for="degree-subject">Degree subject: </label><br>
<select name="degree" id="degree" v-model="userData.degreeSubject">
<option value="maths">maths</option>
<option value="computer-science">computer science</option>
<option value="english">english</option>
<option value="drama">drama</option>
</select>
</div>
</div>
<div class="user-output">
<p>fullname: {{ fullName }}</p>
</div>
</div>
</template>
<script lang="ts">
import { Options, Vue } from 'vue-class-component';
import { Watch } from 'vue-property-decorator';
@Options({
props: {
msg: String
}
})
export default class FakeProfile extends Vue {
msg!: string
private userData = {
firstName: 'John',
secondName: 'Doe',
age: 31,
location: 'Essex',
dateOfBirth: '18/01/1993',
degreeSubject: '',
hasDegree: false
}
/*
Example of a getter and setter for computed properties
*/
get fullName() : string {
return this.userData.firstName + ' ' + this.userData.secondName;
}
/*
takes in the newValue for fullName we then split it to update the first and
last name.
*/
set fullName(newValue: string) {
let names = newValue.split(' ')
this.userData.firstName = names[0]
this.userData.secondName = names[names.length - 1]
}
/*
example of a watcher being used to display new selected degree value.
*/
@Watch('userData.degreeSubject')
degreeChanged(newVal: string) : void {
this.userData.degreeSubject = newVal
alert(`degree subject updated to ${newVal}`)
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.user-data-wrapper, .user-update-wrapper {
font-weight: 500;
display: inline-block;
vertical-align: top;
}
.page-wrapper {
margin: auto;
width: 700px;
}
</style>
【问题讨论】:
标签: vue.js