Vue的watch属性
Vue的watch属性可以用来监听data属性中数据的变化
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="lib/vue.min.js"></script>
<script src="lib/vue-router-3.0.1.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model="firstname" />
</div>
<script type="text/javascript">
var vm = new Vue({
el:"#app",
data:{
firstname:"",
lastname:""
},
methods:{},
watch:{
firstname:function(){
console.log(this.firstname)
}
}
})
</script>
</body>
</html>
可以从上述代码中实践得知,输入框内的值变化多少次,控制台就会打印多少次
同时还可以直接在监听的function中使用参数来获取新值与旧值
watch:{
firstname:function(newValue,OldValue){
console.log(newValue);
console.log(OldValue);
}
}
其中第一个参数是新值,第二个参数是旧值
同时Watch还可以被用来监听路由router的变化,只是这里的监听的元素是固定的
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="lib/vue.min.js"></script>
<script src="lib/vue-router-3.0.1.js"></script>
<style type="text/css">
</style>
</head>
<body>
<div id="app">
<!--
由于Vue-router的hash匹配原则所以我们需要在原定义的路径上加一个#号
-->
<!-- <a href="#/login" rel="external nofollow" >登录</a>
<a href="#/register" rel="external nofollow" >注册</a>-->
<router-link to="/login" tag="span">登录</router-link>
<router-link to="/register">注册</router-link>
<router-view></router-view>
</div>
</body>
<script>
var login={
template:'<h2>登录组件</h2>'
}
var register={
template:'<h2>注册组件</h2>'
}
var routerObj = new VueRouter({
routes:[
//此处的component只能使用组件对象,而不能使用注册的模板的名称
{path:"/login",component:login},
{path:"/register",component:register}
]
})
var vm = new Vue({
el:'#app',
data:{
},
methods:{
},
router:routerObj,//将路由规则对象注册到VM实例上
watch:{
'$route.path':function(newValue,OldValue){
console.log(newValue);
console.log(OldValue);
}
}
})
</script>
</html>
计算属性Computed的作用
computed属性的作用与watch类似,也可以监听属性的变化
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="lib/vue.min.js"></script>
<script src="lib/vue-router-3.0.1.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model="firstname" />
<input type="text" v-model="lastname" />
<input type="text" v-model="fullname" />
</div>
<script type="text/javascript">
var vm = new Vue({
el:"#app",
data:{
firstname:"",
lastname:""
},
methods:{},
/* watch:{
firstname:function(newValue,OldValue){
console.log(newValue);
console.log(OldValue);
}
}*/
computed:{
fullname:function(){
return this.firstname +"-"+this.lastname
}
}
})
</script>
</body>
</html>
只是他会根据他依赖的属性,生成一个属性,让vm对象可以使用这个属性
methods,watch,computed的区别
总结
以上所述是小编给大家介绍的Vue的watch和computed方法的使用及区别介绍,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对亿速云网站的支持!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。