写 Nuxt 遇到的两个小问题

2024-03-20 · 周三一般多云

今天在公司做的事情是继续看 Glarity 项目的代码,以及研究谷歌翻译 API 的调用和对现有插件逻辑的接入,前者直接参考竞品的请求数据就完了,后者还需要重构业务代码,因为之前他们写的逻辑是面向过程单一的获取 YouTube 字幕,其中部分逻辑需要提炼出来复用。

晚上写了一阵子 Nuxt,主要遇到两个问题。一个是原先代码设计的问题,不能用 React 思维写 Vue,服务器执行一次 defineComponent 函数之后客户端就不会再执行了,如果数据需要转换,要么修改 useFetch 增加 transform 调整,要么使用 computed 格式化数据。

const state = reactive({
  data: [],
  months: [],
});

const { data } = await useFetch<API.Response<API.Note.INoteTimelineData[]>>(`/api/note/timeline`, {
  query,
});

// 👎 只会在服务器执行一次
if (data.value) {
  const [notes, months] = parseTimeline(data.value.data);

  state.data = notes;
  state.months = months;
}

// 👍 客户端和服务端都会正常执行渲染
const computedData = computed<IComputedData>(() => (
  data.value ? parseTimeline(data.value.data) : [[], []]
));

第二个问题是改为 Nuxt 渲染之后才出现的问题,发现我日记页动态插入的“时间轴”链接按钮消失了。

onBeforeMount is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.

主要是组件变成了 async 的,需要等待服务器端获取数据才渲染组件,这个警告的意思就是遇到 await 的 Hooks 之前就得先执行这个 Hooks,否则 onBeforeMount 的内容就不会执行。把代码改成下面的次序就可以解决问题。

// 我封装的 Hooks,里面有一个 onBeforeMount 的调用
useAction();

// Nuxt 的数据请求 Hooks
const { data } = await useFetch();
Paul

Paul

特立独行的一只前端菜狗。这篇日记编写大概耗时了 14 分钟,内容均为个人原创,并采用 CC BY-NC-SA 4.0 授权协议,转载请注明来源,谢谢!如本站内容对你有所帮助的话,不妨 捐助支持 一下?

奇趣音乐盒技术源于 Kico Player
Emmm,这里是歌词君