本代码适用于移动端商城场景,可用于展示商品信息、店铺信息以及相关功能,如商品详情页、店铺详情页、购物车等。通过精美的卡片设计,为用户提供直观且交互友好的购物体验。
本代码的主要功能包括:
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import { createPinia } from 'pinia'
import { ref, onMounted } from 'vue'
首先,导入 Vue.js、Vue Router、Pinia 和 Vue 核心库。
const app = createApp({
setup() {
// ...
},
render() {
return h(App)
}
})
创建 Vue 实例并定义其 setup 和 render 函数。
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
component: Home
},
{
path: '/product/:id',
component: ProductDetail
},
{
path: '/shop/:id',
component: ShopDetail
},
{
path: '/cart',
component: Cart
}
]
})
创建 Vue Router 实例并定义路由规则。
const pinia = createPinia()
创建 Pinia 状态管理库。
const products = ref([])
const shops = ref([])
onMounted(() => {
// 获取数据并填充到响应式变量中
})
使用 Vue 的 ref 和 onMounted 钩子来获取数据并填充到响应式变量中。
<template>
<div class="card">
<div class="card-header">
<img :src="product.image" alt="">
<div class="card-title">{{ product.name }}</div>
</div>
<div class="card-body">
{{ product.description }}
</div>
<div class="card-footer">
<button @click="addToCart">加入购物车</button>
</div>
</div>
</template>
export default {
props: ['product'],
methods: {
addToCart() {
// 添加商品到购物车
}
}
}
定义一个 Vue 组件来渲染卡片,并通过 props 传入数据。
const cart = ref([])
const addToCart = (product) => {
// 将商品添加到购物车
}
使用 Vue 的 ref 来管理购物车状态,并定义一个 addToCart 方法来将商品添加到购物车。