在页面重新加载时,当正在监视的属性未更改时,Vue监视不会运行


<template>
<!-- The navbar has a property for gender, the color of the navbar will change depending on the 
gender -->
<!-- pass the props gender through a form submission and event -->
<div class="nav-main" :class="{female: isGirl, male: isBoy}">
<nav class="menu">
<a href="#">Home</a>
<a href="#">Find</a>
<a href="#">Match</a>
</nav>
<nav class="settings">
<a href="#" class="setting-link">Settings</a>
</nav>
</div>
</template>
<script>
export default {
name: 'Navbar',
props: ['gender'],
data(){
return{
isBoy: false,
isGirl: false,
}
},
watch: {
gender: function(){
if(this.gender === 'male'){
this.isGirl = false
this.isBoy = true
return 0
}else{
this.isBoy = false
this.isGirl = true
return 0
}
}
}
}
</script>
<style scoped>
.nav-main{
padding: 20px 0;   
display: grid;  

}
nav{
display: inline-block;
}
.menu{
grid-column: 1/4;
text-align: right;
}
.settings{
grid-column: 4/6;
text-align: right;
}
a{
color: white;
text-decoration: none;
padding: 0  50px;
font-family: 'Nunito', sans-serif;
}
.female{
background: #ffb6c1;
}
.male{
background: #4169e1;
}
</style>

我计划做的是,如果属性"性别"中传递的值是男性,则在导航栏上应用类别男性,但如果有其他内容,则将应用类别女性这运行得很好,每当我更改属性时,事情都会按计划进行,但每当我重新加载页面时,watch函数不会触发,值保持不变为什么会发生这种情况,我该如何解决。

比如说,如果我把道具传给男性,那么男性等级就被应用,如果我将道具改为女性,那么女性等级就会被应用,但现在如果我重新加载页面,那么什么都不会发生

在您的案例中,推荐的模式是计算属性,将isBoyisGirl更改为基于genderprop:的计算属性

props: ['gender'],
computed: {
isBoy() {
return this.gender==='male'
},
isGirl() {
return !this.isBoy
}
}

代码较短,计算的属性对道具的更改作出反应。

使用computed的方式很好。watch功能不起作用的原因可能是prop:gender在手表代码开始工作之前发生了更改。所以尝试使用watch的选项immediate: true

最新更新