vue.js基础__ watch 选项
Posted sunyang-001
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue.js基础__ watch 选项相关的知识,希望对你有一定的参考价值。
watch 选项主要用于数据监控,有两种书写方式:
一种是写在构造器内部,另一种是在构造器外部使用
下面以监控天气为例,代码如下:
- 每次加减5°C,在watch内部做 if 判断
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>watch option</title>
<script src="../assets/js/vue.js"></script>
</head>
<body>
<h1>watch option</h1>
<hr>
<div id="app">
<p>今日温度:temperature°C</p>
<p>建议:proposal</p>
<p><button @click="add">add</button>
<button @click="reduce">reduce</button></p>
</div>
<script>
var proposalArr = [‘T恤短袖‘, ‘夹克长裙‘, ‘棉衣羽绒服‘]
var app = new Vue(
el: ‘#app‘,
data:
temperature: 14,
proposal: ‘夹克长裙‘
,
methods:
add()
this.temperature += 5
,
reduce()
this.temperature -= 5
,
// watch:
// temperature(newVal, oldVal)
// if (newVal > 26)
// this.proposal = proposalArr[0]
// else if (newVal < 26 && newVal > 0)
// this.proposal = proposalArr[1]
// else
// this.proposal = proposalArr[2]
//
//
//
)
app.$watch(‘temperature‘, function (newVal, oldVal)
if (newVal > 26)
this.proposal = proposalArr[0]
else if (newVal < 26 && newVal > 0)
this.proposal = proposalArr[1]
else
this.proposal = proposalArr[2]
)
</script>
</body>
</html>
以上是关于vue.js基础__ watch 选项的主要内容,如果未能解决你的问题,请参考以下文章
谈谈vue.js中methods watch和compute的区别和联系