头图

watch可以直接监听ref类型的数据,如果监听reactive会黄字警告
image.png
你需要将reactive解构出来监听

const state = reactive({
  tagsList: [],
  currentTags: ""
})

// 监听当前Tags项
let { currentTags } = toRefs(state)
watch(currentTags, (newV, oldV) => {
  console.log("数据变了", newV, oldV)
})

关于监听数据的问题,这篇文章有写:https://blog.csdn.net/moxunjinmu/article/details/123219081
watch中调用异步函数会报错,如果你想在watch中调用异步函数,需要设置 flush: 'post'

watch(currentTags, (newV, oldV) => {
  toTags(newV); // 你自定义的异步函数
},{ flush: 'post' })

监听props

const props = defineProps({
  projectDetail: {
    type: Object,
    default: () => {},
  }
});


watch(
  () => props.projectDetail,
  (newV, oldV) => {
    console.log(newV);
  }
);

监听计算属性computed

const isCheck = computed(() => {
  return projectDetail.value.projectStatus ? true : false;
});

watch(isCheck, (newV, oldV) => {
   console.log(newV);
});

一个页面可以写多个监听

watch(
    () => props.projectId,
    (newV, oldV) => {
        console.log("监听项目id", newV);
    }
  }
);

watch(
    () => props.fileTypeList,
    (newV, oldV) => {
        console.log("监听文件类型", newV);
    }
);

兔子先森
388 声望17 粉丝

致力于新技术的推广与优秀技术的普及。