v-model 的值变化,为何会造成 html页面的 Math.random() 变化

v-model 的值变化,为何会造成 html页面的 Math.random() 变化?

阅读 4.7k
3 个回答

这样的改变是vue所期望的。这大概是因为vue2中是用 render(){}方法,当你用vue的{{Math.random()}}或其他的vue指令绑定时,包括v-if,当template改变时都会被调用,当用vue的click改变 template时,整个template的DOM将重新计算,所以就又调用了Math.random()重新得到新的值,如果你用data中 msg: Math.random() 这样是不会重新计算的。

示例代码:


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <style>
    [v-cloak] {
        display: none;
    }
    </style>
</head>

<body>
    <div id="example">
        <div v-if="Math.random() >= 0.5">
            Now you see me
        </div>
        <div v-else>
            Now you don't
        </div>
        <div v-show="loginType==='username'">
            <label>Username</label>
            <input type="text" placeholder="Enter your username" key="username-input">
        </div>
        <div v-show="loginType==='email'">
            <label>Email</label>
            <input type="text" placeholder="Enter your email address" key="email-input">
        </div>
        <button @click="toggleLoginType">Toggle login type</button>
    </div>

    <script src="https://cdn.bootcss.com/vue/2.3.4/vue.js"></script>
    <script src="https://cdn.bootcss.com/axios/0.16.2/axios.js"></script>
    <script src="https://cdn.bootcss.com/lodash.js/4.17.4/lodash.js"></script>
    <script>
    var vm = new Vue({
        el: '#example',
        data: {
            loginType: 'username'
        },
        methods: {
            toggleLoginType: function() {
                if (this.loginType === 'username') {
                    this.loginType = 'email';
                } else {
                    this.loginType = 'username'
                }
            }   
        }
    })

    </script>
</body>

</html>

@海岛心hey

data中定义一个变量用来接收Math.random()的值吧

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