vue3+vite+ts 仿淘宝放大镜效果完整代码
时间: 2024-12-24 17:33:30 浏览: 15
在 Vue3、Vite 和 TypeScript 的环境中,创建一个简单的商品图片放大镜效果,你可以按照以下步骤和伪代码来构建:
首先,安装依赖:
```sh
npm install @vue/cli vite ts vue-class-component vue-router axios
```
然后,在`src/main.ts`中配置Vue和路由:
```typescript
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
createApp(App)
.use(router)
.mount('#app');
```
接着,在`src/router/index.ts`里设置路由(假设有一个商品详情页`ProductDetail`):
```typescript
import { createRouter, createWebHistory } from 'vue-router';
import ProductDetail from './views/ProductDetail.vue';
const routes = [
{
path: '/product/:id',
name: 'productDetail',
component: ProductDetail,
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
```
在`src/views/ProductDetail.vue`文件中,我们可以实现放大镜效果:
```html
<template>
<div class="product-detail">
<img :src="imageUrl" ref="image" />
<div v-if="showMagnifier" class="magnifier">
<img src="magnifier.png" :style="{ transform: magnifierPosition }" />
</div>
</div>
</template>
<script lang="ts">
import { Component, Prop, Ref, computed } from 'vue';
import axios from 'axios';
@Component
export default class ProductDetail extends Vue {
@Prop() productId: string;
imageUrl!: string;
magnifierImageRef!: HTMLImageElement;
showMagnifier = false;
magnifierPosition = '';
mounted() {
// 异步获取图片地址
axios.get(`/api/products/${this.productId}`).then((res) => {
this.imageUrl = res.data.mainImage;
});
}
onMouseEnter() {
this.showMagnifier = true;
}
onMouseLeave() {
this.showMagnifier = false;
this.magnifierPosition = '';
}
onMagnifierMouseMove(event: MouseEvent) {
const rect = this.$refs.image.getBoundingClientRect();
const xDiff = event.clientX - rect.left;
const yDiff = event.clientY - rect.top;
this.magnifierPosition = `translate(${xDiff}px, ${yDiff}px)`;
}
}
</script>
<style scoped>
.product-detail {
position: relative;
}
.magnifier {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
cursor: zoom-in;
opacity: 0.5;
}
</style>
```
这个例子中,当鼠标进入图片区域时,显示一个模拟的放大镜,并随着鼠标移动调整位置。实际项目中可能需要处理更多细节,比如缩放动画等。
阅读全文