vue3 watch记录

94 阅读1分钟

常规写法

watch(current, () => {
  getNavTitleCache()
})

异步写法

watch(data, async () => {
  await initItem()
  render(listBox.value.scrollTop)
}, { deep: true })

对于prop的监听 prop为数组形式

const props = defineProps({
  value: {
    type    : Array,
    required: true,
    default : () => []
  },
  
  //第一步传入值发生变化
watch(() => props.value, () => {
  //赋值data内的值
  imageArr.value = props.value
})

对于data的监听 data为数组


watch(() => [ ...imageArr.value ], () => {
  emit('update:value', imageArr.value)
})

对于prop的监听 同时 深度监听

watch(
  () => props.point,
  () => {
    mapAddPointer();
  },
  { deep: true },
);

对于普通prop的监听 同时

watch(
  () => props.point,
  () => {
    mapAddPointer();
  },
);

监听路由

import { useRouter } from 'vue-router';
const router = useRouter();

watch(
  () => router.currentRoute.value.path,
  (newValue) => {
  },
  { immediate: true }
)