这是我参与8月更文挑战的第10天,活动详情查看:8月更文挑战
vue3中使用watch注意事项
编写watch函数需要编写两个参数,第一个是要监听的值,然后是一个回调函数。在函数中你可以获得到新知和老值。
使用watch的时候同样需要先导入
- 监听使用ref定义的变量的时候时候,第一个参数直接使用
import {... , watch} from "vue"
setup() {
const selectGirl = ref("");
const data = reactive({
girls: ["a", "b", "c"],
selectGirlFun: (index) => {
selectGirl.value = data.girls[index];
},
});
const refData = toRefs(data);
watch(selectGirl,(newValue, old) => {
console.log(1111,newValue,old)
});
return {
...refData,
selectGirl
};
},
复制代码
- 使用reactive定义的变量需要没在监听的时候需要使用
函数返回值
的形式才能监听到
setup() {
const data = reactive({
girls: ["a", "b", "c"],
selectGirl: "",
selectGirlFun: (index) => {
data.selectGirl = data.girls[index];
},
});
const refData = toRefs(data);
onRenderTriggered((event) => {
console.log("状态触发组件--------------->");
console.log(event);
});
watch(()=> data.selectGirl,(newValue, old) => {
console.log(1111,newValue,old)
});
return {
...refData,
};
},
复制代码
如果想要deep监听,
vm.$watch('someObject', callback, {
deep: true
})
vm.someObject.nestedValue = 123
复制代码
immediate
vm.$watch('a', callback, {
immediate: true
})
复制代码
注意,在带有 immediate 选项时,你不能在第一次回调时取消侦听给定的 property。
const unwatch = vm.$watch(
'value',
function() {
doSomething()
unwatch()
},
{ immediate: true }
)
复制代码
监听多个变量
参数需要写成数组的形式,同事返回的参数也是数组
setup() {
const data = reactive({
girls: ["a", "b", "c"],
selectGirl: "",
selectGirlFun: (index) => {
data.selectGirl = data.girls[index];
},
});
const refData = toRefs(data);
onRenderTriggered((event) => {
console.log("状态触发组件--------------->");
console.log(event);
});
watch([()=> data.girls,()=> data.selectGirl],(newValue, old) => {
console.log(1111,newValue[1],old[1])
});
return {
...refData,
};
},
复制代码
其实与 watch 类似的 API 还有一个就是:watchEffect,立即执行传入的一个函数,并响应式追踪其依赖,并在其依赖变更时重新运行该函数。
<template>
<button @click="change">count is: {{ state.count }}</button>
</template>
<script>
import { reactive, watchEffect } from 'vue'
export default {
setup () {
let state = reactive({count: 0})
let change = () => state.count++;
watchEffect(() => {
console.log(state.count, '改变')
})
return { state, change }
}
}
</script>
复制代码
区分两者的区别
1、watch 是需要传入侦听的数据源,而 watchEffect 是自动收集数据源作为依赖。
2、watch 可以访问侦听状态变化前后的值,而 watchEffect 没有。
3、watch 是属性改变的时候执行,而 watchEffect 是默认会执行一次,然后属性改变也会执行。
vue3-HOOKS模块化处理
vue3版本的更新,就是能搞更好的重用机制,可以把想要得模块独立出去
eg:显示一个当前时间的工能,在多个页面需要调用的时候不用重复的调用
可以在src
目录下,新建一个文件夹hooks
(所有抽离出来的功能模块都可以放到这个文件夹里),
然后再新建一个文件useNowTime.js
,这里使用use开头是一个使用习惯,代表是一个抽离出来的模块
import { ref } from "vue";
const nowTime = ref("00:00:00");
const getNowTime = () => {
const now = new Date();
const hour = now.getHours() < 10 ? "0" + now.getHours() : now.getHours();
const minu =
now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes();
const sec =
now.getSeconds() < 10 ? "0" + now.getSeconds() : now.getSeconds();
nowTime.value = hour + ":" + minu + ":" + sec;
setTimeout(getNowTime, 1000);
};
export { nowTime, getNowTime }
复制代码
注意:需要将定义的变量nowTime
和方法getNowTime
通过export导出
使用的时候跟在setup中定义的变量和方法一样使用
使用模块化封装一个远程调用接口的组件
建立useURLAxios.js文件
在文件中定义远程加载需要的 变量和axios请求
import {ref} from 'vue'
import axios from 'axios';
function usURLAxios(url) {
const result = ref(null)
const loading = ref(true)
const loaded =ref(false)
const error =ref(null)
axios.get(url).then((res)=>{
loading.value = false
loaded.value = true
result.value = res.data
}).catch(e=>{
error.value = e
loading.value = false
})
return {
result,
loading,
loaded,
error
}
}
export default usURLAxios
复制代码
使用时
新增一个.vue
文件
<template>
<div>
<button @click="getImg">随机展示图片</button>
<div v-if="thisloading">Loading.....</div>
<img v-if="thisloaded" :src="https://juejin.cn/post/thisresult.message" />
<div></div>
</div>
</template>
<script>
import { reactive, toRefs } from "vue";
import useUrlAxios from "../hooks/useURLAxios";
export default {
setup() {
const data = reactive({
thisresult: null,
thisloading: true,
thisloaded: false,
getImg: () => {
const { result, loading, loaded } = useUrlAxios(
"https://dog.ceo/api/breeds/image/random"
);
data.thisresult = result;
data.thisloading = loading;
data.thisloaded = loaded;
console.log(
22222,
data.thisresult,
data.thisloading,
data.thisloaded,
result,
loaded,
loading
);
},
});
const refData = toRefs(data);
return { ...refData };
},
};
</script>
<style lang="scss" scoped>
</style>
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END