vue3 watch([props.id,], getData); 监听props数据变化后请求接口

vue yekong 583℃

项目开发中,使用vue3的写法时,使用watch监听props没有触发接口请求

在 Vue 3 中,由于一些性能优化,watch 不会监听到 props 的变化。对于这种情况,可以使用 watchEffect 来替代 watch。下面是代码修改后的版本:

<script setup>
import { ref, watchEffect, onMounted, defineProps } from 'vue';
import {dts_data_list} from "@/api/api/user.js";
import { useCounterStore } from '@/store/counter.js'

// 定义属性
const props = defineProps({
  id: {
    type: String,
    default: ''
  },
  end: {
    type: String,
    default: ''
  },
  start: {
    type: String,
    default: ''
  },
});

const list = ref([]);
const counterStore = useCounterStore();

const getData = async () => {
  try {
    const res = await dts_data_list({
      infoId: props.id,
      pageNum: 1,
      pageSize: 10,
      startTime: props.start,
      endTime: props.end
    });
    list.value = res.rows;
    counterStore.setDataList(res.rows)
  } catch (err) {
    console.error(err);
  }
};

watchEffect(() => {
  getData();
});
</script>

这段代码中,我用 watchEffect 替换了 watchwatchEffect 会立即运行传入的函数,然后响应性地再次运行它每当它的依赖项发生变化。

需要注意的是,watchEffect 会立即执行一次 getData,所以我去掉了 onMounted(getData)

如果你对watchEffect 和 watch的区别,感兴趣的话,也可以查看一下。

喜欢 (0)