Vue3监听属性
我们可以通过watch来响应数据的变化。
<!--
* @Date: 2023-04-02 19:41:53
* @LastEditors: Mei
* @LastEditTime: 2023-04-02 19:50:34
* @FilePath: \vscode\Vue3_listen.html
* @Description:
*
* Copyright (c) 2023 by ${git_name_email}, All Rights Reserved.
-->
<!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">
<title>Document</title>
<script src="vue_doc/vue.global3.js"></script>
</head>
<body>
<div id="app">
<p >计数器:{{counter}}</p>
<button @click="counter++" >点我</button>
</div>
<script>
const app={
data(){
return{
counter:1
}
}
}
vm=Vue.createApp(app).mount('#app')
vm.$watch('counter',function(a,b){
alert('数字变化,后面的编程前面的:'+b+'编程'+a+'!!!!!!')
})
</script>
</body>
</html>
以下实例进行千米和米之间的换算:
<!--
* @Date: 2023-04-02 19:41:53
* @LastEditors: Mei
* @LastEditTime: 2023-04-03 09:31:26
* @FilePath: \vscode\Vue3_listen.html
* @Description:
*
* Copyright (c) 2023 by ${git_name_email}, All Rights Reserved.
-->
<!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">
<title>Document</title>
<script src="vue_doc/vue.global3.js"></script>
</head>
<body>
<div id="app">
<!-- <p >计数器:{{counter}}</p>
<button @click="counter++" >点我</button> -->
千米:<input type="text" v-model="kilometers" @focus="currentlyActiveField='kilometers'">
米:<input type="text" v-model="meters" @focus="currentlyActiveField='meters'">
</div>
<p id="info"></p>
<script>
const app={
data(){
return{
// counter:1
kilometers:0,
meters:0
}
},
watch:{
meters:function(newValue,oldValue){
if(this.currentlyActiveField==='meters'){
this.kilometers=newValue/1000;
this.meters=newValue;
}
},
kilometers:function(newValue,oldValue){
if(this.currentlyActiveField==='kilometers'){
this.kilometers=newValue;
this.meters=newValue*1000;
}
}
}
}
vm=Vue.createApp(app).mount('#app')
vm.$watch('kilometers',function(a,b){
document.getElementById("info").innerHTML='数字变化,修改前的值是:'+b+'修改后的值是'+a+'!!!!!!'
})
</script>
</body>
</html>
异步加载中使用watch
异步数据的加载Vue通过watch选项提供了一个更通用的方法,来响应数据的变化。
以下实例我们使用axios库
<script>
const watchExampleVM = Vue.createApp({
data() {
return {
question: '',
answer: '每个问题结尾需要输入 ? 号。'
}
},
watch: {
// 每当问题改变时,此功能将运行,以 ? 号结尾,兼容中英文 ?
question(newQuestion, oldQuestion) {
if (newQuestion.indexOf('?') > -1 || newQuestion.indexOf('?') > -1) {
this.getAnswer()
}
}
},
methods: {
getAnswer() {
this.answer = '加载中...'
axios
.get('/try/ajax/json_vuetest.php')
.then(response => {
this.answer = response.data.answer
})
.catch(error => {
this.answer = '错误! 无法访问 API。 ' + error
})
}
}
}).mount('#watch-example')
</script>