v-model 的值变化,为何会造成 html页面的 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>
9 回答1.8k 阅读✓ 已解决
6 回答1.8k 阅读
3 回答1.5k 阅读✓ 已解决
4 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读
2 回答1.3k 阅读✓ 已解决
3 回答1.5k 阅读✓ 已解决
这样的改变是vue所期望的。这大概是因为vue2中是用
render(){}
方法,当你用vue的{{Math.random()}}
或其他的vue指令绑定时,包括v-if
,当template改变时都会被调用,当用vue的click改变 template时,整个template的DOM将重新计算,所以就又调用了Math.random()
重新得到新的值,如果你用data中msg: Math.random()
这样是不会重新计算的。