今天在看Vue的官方Doc,然后照着上面的例子写了点demo,但是关于v-if条件渲染
有点疑惑,我的代码如下:
<div id="demo1">
<div v-if="Math.random() > 0.5">
Now you see me
</div>
<div v-else>
Now you don't
</div>
<template v-if="loginType === 'Username'">
<label>{{ loginType }}</label>
<input type="text" placeholder="Enter your username" key="username-input">
</template>
<template v-else>
<label>{{ loginType }}</label>
<input type="text" placeholder="Enter your email" key="email-input">
</template>
<button v-on:click="changeLoginType">Toggle login type</button>
</div>
// 此处忽略一些代码
<script>
var watch_example = new Vue({
el: '#demo1',
data: {
loginType: 'Username',
},
methods: {
changeLoginType: function () {
this.loginType == 'Username' ? this.loginType = 'Email' : this.loginType = 'Username'
}
}
})
</script>
说明:Vue.js版本:v2.5.1
我的问题是:
当我点击button
的时候,changeLoginType()
函数可以成功执行,但是也同时触发到了代码中的第一个v-if
,就是那个Math.random()
函数
没点击之前效果:
点击之后(由于是random()
随机的,效果不是每次都有,但足以说明random()
函数是执行了的):
因为你点击了按钮以后,loginType一定会改变,状态的改变会导致重新render,所以会执行到random