0
点赞
收藏
分享

微信扫一扫

watch初体验


watch可以监控元数据的变化,当元数据变化时执行相关函数

<!--
* @Description: watch练习
* @Autor: leechoy
* @Date: 2022-01-19 02:02:43
* @IDE: Visual Studio Code
-->
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.staticfile.org/vue/3.0.5/vue.global.js"></script>
<title>Document</title>
</head>

<body>
<div id="app">
<h1>{{name}}</h1>
<button @click='change'>switch</button>
<div>
<input type="text" v-model='inputContent'>
</div>
{{remoteMsg}}
</div>
</body>
<script>
var vm = {
data() {
return {
name: 'you have not set your name.',
inputContent: '',
remoteMsg: ''
}
},
methods: {
change($event) {
console.log($event);
this.name = 'leechoy'
}
},
watch: {
name(newValue, oldValue) {
alert('you have turn the name to ' + newValue);
},
inputContent(newValue) {
console.log(this.inputContent);
}
}
}
Vue.createApp(vm).mount("#app");
</script>

</html>

watch初体验_vue.js

watch选项还可以用在异步获取数据上,此下面为一个案例,watch可以用于输入框实时检索提示内容

watch: {
name(newValue, oldValue) {
alert('you have turn the name to ' + newValue);
},
inputContent(newValue) {
console.log(this.inputContent);
axios({
method: 'GET',
url: '/xxxx',
params: {
keyword: newValue
}
}).then(res => {
this.remoteMsg = res.data.message;
})
}
}


举报

相关推荐

0 条评论