vue中监视属性主要用于监视属性的变化,如:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title> Vue学习第二天 </title>
<script type="text/javascript" src="../js/vue.js"></script>
<!-- 引入样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<style>
</style>
</head>
<body>
<div id="root">
<h2>今天天气很{{info}}</h2>
<button @click="isHot = !isHot">切换</button>
<hr />
{{date.year}}年{{date.month}}月{{date.day}}日
<br>
<br>
<button @click="date.year++">年++</button></button></button>
<button @click="date.month++">月++</button>
<button @click="date.day++">日++</button>
</div>
<script type="text/javascript">
const vm = new Vue({
el: '#root',
data() {
return {
date: {
year: "1998",
month: "2",
day: "8"
},
isHot: true
}
},
// 所有的方法都要放在这里,标识被vue管理
methods: {
change() {
this.isHot = !this.isHot;
}
},
computed: {
info: function () {
return this.isHot ? "炎热" : "凉快";
}
},
watch: {
// 需要监听的目标
isHot: {
// 初始化调用handler
// immediate: true,
// 调用时机:监视的目标改变时触发
handler(newValue, oldValue) {
console.log("isHot发生改变,内置形式:", oldValue, newValue)
}
},
// 单独监视对象中的某一个属性
'date.year': {
handler(nValue, oValue) {
console.log("年改变:", nValue, oValue)
}
},
// 对象深度监视
date: {
// 深度监视
deep: true,
handler(nValue, oValue) {
console.log("对象中的属性发生了变化");
}
},
// 简写,仅在不需要其他额外配置项的情况下使用
// 此函数相当于handler函数
'date.month'(nValue, oValue) {
console.log("月改变:", nValue, oValue)
}
}
});
// 也可以这样监视
// 完整写法
vm.$watch('isHot', {
// 初始化调用handler
// immediate: true,
// 调用时机:监视的目标改变时触发
handler(newValue, oldValue) {
console.log("isHot发生改变,外置形式:", oldValue, newValue)
}
})
vm.$watch('isHot', function (newValue, oldValue) {
console.log("isHot发生改变,外置形式,简写方式", oldValue, newValue)
})
</script>
</body>
</html>
注意如果是多级嵌套的对象,需要将deep设置为true的方式进行监视
watch和computed区别
- watch可以实现computed的所有功能,但很多情况下computed的写法要比watch简单
- watch可以异步的处理数据,但computed不能(异步计算使用watch)