这个主要是解决nuxt3下的图片缩放的问题的,本来使用viewerjs挺好的,但是奈何nuxt3太调皮了,问题多,转而使用这个zoom
1.安装
yarn add --dev medium-zoom
2.配置 Add following client-side (file name suffix .client.(ts|js)) plugin: ./plugins/medium-zoom.client.ts 注意这个client前缀,表示当process.client的时候才会加载,还是很有用的,之前一直没能弄明白这个前缀干啥用的
import { defineNuxtPlugin } from '#app'
import mediumZoom, { Zoom } from 'medium-zoom'
export default defineNuxtPlugin((nuxtApp) => {
const selector = '.image-zoomable'
const zoom: Zoom = mediumZoom(selector, {})
// (re-)init for newly rendered page, also to work in SPA mode (client-side routing)
nuxtApp.hook('page:finish', () => {
zoom.detach(selector)
.attach(selector)
})
// make available as helper to NuxtApp
nuxtApp.provide('mediumZoom', zoom)
})
3.解释
Now for each page rendered / client-side navigated to, medium-zoom is applied accordingly for all images in the DOM matching the chosen selector. In our plugin we chose a CSS selector to match all img elements with the class image-zoomable.
You can find all supported selector types in the module's docs.
Running on nuxt - client-side app navigation is done via vue-router. For medium-zoom to do it's magic, it has to be 're-attached' following changes to image on the page. We use the page:finish nuxt3 lifecycle hook as a trigger.
Finally, we also provide the mediumZoom instance as a helper.
4.使用
<img src="/images/fluffy-cat.jpg" alt="A fluffy cat" class="image-zoomable" />,必须加上 class="image-zoomable",方便上面的ts选择图片
5.注意
需要特别注意的是,这个img的src内容,需要再页面加载完成的时候,或者 之前就把img的src数据渲染出来,不能使用await 获取数据,否则上面的ts 不生效,我分析了原因
可能是上面的ts 会在 nuxtApp添加 hook page:finish,所以我的解决办法是通过middleware 调用 获取数据存储到localstorage 然后在mounted 中取出数据,进行渲染。
