This is the 10th day of my participation in the August More text Challenge. For details, see: August More Text Challenge
Precautions for using watch in VUE3
Writing the watch function requires writing two arguments, the first being the value to listen on, and then a callback function. You can get new and old values in the function. When using watch, you also need to import
- When listening for variables defined by ref, the first argument is used directly
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 }; },Copy the code
- The variable defined by using reactive needs to be used when not listening
Function return value
In order to be heard
setup() { const data = reactive({ girls: ["a", "b", "c"], selectGirl: "", selectGirlFun: (index) => { data.selectGirl = data.girls[index]; }}); const refData = toRefs(data); OnRenderTriggered (= > {(event). The console log (" state trigger components -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- > "); console.log(event); }); watch(()=> data.selectGirl,(newValue, old) => { console.log(1111,newValue,old) }); return { ... refData, }; },Copy the code
If you want to deep listen,
vm.$watch('someObject', callback, {
deep: true
})
vm.someObject.nestedValue = 123
Copy the code
immediate
vm.$watch('a', callback, {
immediate: true
})
Copy the code
Note that with the immediate option, you cannot cancel listening on the given property on the first callback.
const unwatch = vm.$watch(
'value',
function() {
doSomething()
unwatch()
},
{ immediate: true }
)
Copy the code
Listening to multiple variables
The arguments need to be written as arrays, and the arguments returned are arrays
setup() { const data = reactive({ girls: ["a", "b", "c"], selectGirl: "", selectGirlFun: (index) => { data.selectGirl = data.girls[index]; }}); const refData = toRefs(data); OnRenderTriggered (= > {(event). The console log (" state trigger components -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- > "); console.log(event); }); watch([()=> data.girls,()=> data.selectGirl],(newValue, old) => { console.log(1111,newValue[1],old[1]) }); return { ... refData, }; },Copy the code
Another API similar to Watch is watchEffect, which immediately executes a function that is passed in, responds by tracking its dependencies, and reruns the function if its dependencies change.
<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>
Copy the code
Distinguish between the two
1. Watch is the data source that needs to be passed in for listening, while watchEffect automatically collects the data source as a dependency.
2. Watch can access values before and after a state change, while watchEffect does not.
3. Watch is executed when properties change, watchEffect is executed once by default, and then properties change.
Vue3-hooks are handled modularically
Vue3 version update, which is able to make better reuse mechanism, can put the want independence module eg: according to the work of a current time can, in multiple pages when you need to call don’t have to repeat calls can be under the SRC directory, create a new folder hooks (all of the functional modules can be pulled out of the folder). Then create a new file, usenowtime.js, where use begins with a custom, representing a pulled module
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 }
Copy the code
Note: You need to export the defined variable nowTime and method getNowTime in the same way as the variables and methods defined in setup
A component that uses modularity to encapsulate a remote call interface creates a useurlaxios.js file in which the variables and AXIos requests required for remote loading are defined
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
Copy the code
Add a.vue file when using
<template> <div> < button@click ="getImg"> </button> <div v-if="thisloading">Loading..... </div> <img v-if="thisloaded" :src="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>Copy the code