Vue.js入门疑惑

今天在看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()函数

没点击之前效果:

clipboard.png

点击之后(由于是random()随机的,效果不是每次都有,但足以说明random()函数是执行了的):

clipboard.png


为什么点击button会触发到random()呢?

阅读 2.7k
1 个回答

因为你点击了按钮以后,loginType一定会改变,状态的改变会导致重新render,所以会执行到random

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题