Vue3 + ts + pinia 写的购物车,vite ,webpacke

上图:创建 Vue3指令     vue create [这里是文件名字]进去之后自己选这Vue3  ,千万不要选择Vuex  因为会冲突

 

第一步  创建 vue3项目文件且需要配置pinai,也可以去官方上进行安装教程

npm install pinia --save //安装pinia
npm install pinia-plugin-persist --save //安装pinia-plugin-persist,数据持久化插件

或者

yarn add pinia

接下来是重点啦上

这是我的 package.json   文件可以复制上去 

然后在吧你的node_models删掉,在 下载  npm i 或者  cnpm i

{
  "name": "pinia",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build"
  },
  "dependencies": {
    "pinia": "^2.0.23",
    "vue": "^3.0.0"
  },
  "devDependencies": {
    "@vue/cli-plugin-typescript": "~4.5.15",
    "@vue/cli-service": "~4.5.15",
    "@vue/compiler-sfc": "^3.0.0",
    "less": "^3.0.4",
    "less-loader": "^5.0.0",
    "typescript": "~4.1.5"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead"
  ]
}

在App.vue 中写:

<template>
  <h1> Pinia - 购物车实例2</h1>
  <hr>
  <h2>商品列表</h2>
  <ProductList></ProductList>
  <hr>
  <ShoppingCart></ShoppingCart>
</template>

<script lang="ts" setup>
import ProductList from '@/components/ProductList.vue'
import ShoppingCart from '@/components/ShoppingCart.vue'
</script>
<style>

</style>



 在main.vue 中写:

import { createApp } from 'vue'
import App from './App.vue'

import { createPinia } from 'pinia'


const pinia = createPinia()

createApp(App).use(pinia).mount('#app')

 在 src 中创建 store 且在里面创建:

cart.ts 

import { buyProducts, IProduct } from '@/api/shop'
import { defineStore } from 'pinia'
import { useProductsStore } from './products'
type cartProduct = {
    quantity: number
} & Omit<IProduct, 'inventory'>

export const useCartStore = defineStore('cart', {
    state: () => {
        return {
            cartProducts: [] as cartProduct[], //购物车商品列表
            checkoutStatus: null as null | string
        }
    },
    getters: {
        totalPrice(state) {
            return state.cartProducts.reduce((total, item) => {
                return total + item.price * item.quantity
            }, 0)
        }
    },
    actions: {
        addProductCart(product: IProduct) {
            console.log('addProductToCart', product);

            // 看商品有没有库存
            if (product.inventory < 1) {
                return
            }
            //检查购物车中是否已有该商品
            const cartItem = this.cartProducts.find(item => item.id === product.id)
            // 如果有则让商品的数量 +1
            if (cartItem) {
                cartItem.quantity++
            } else {
                //如果没有则添加到购物车列表中
                this.cartProducts.push({
                    id: product.id,
                    title: product.title,
                    price: product.price,
                    quantity: 1  // 第一次加到购物车的商品的数量就是  1 
                })
            }
            // 更新商品的库存

            // product.inventory--       //  不建议这样使用

            const productsStore = useProductsStore()
            productsStore.decrementProduct(product)
        }
        ,
        async checkout() {
            const ret = await buyProducts()
            this.checkoutStatus = ret ? '成功' : '失败'
            if(ret){
                this.cartProducts = []
            }
        }
    }

})

products.ts

import { defineStore } from 'pinia'
import { getProducts, IProduct } from '@/api/shop'



export const useProductsStore = defineStore('products', {
    state: () => {
        return {
            // 这里有一个ts  的类型问题   所有我们要通过 api  中的类型导入过来  告诉 all 的类型是   IProduct[]
            all: [] as IProduct[] // 所有的商品列表  
        }
    },
    getters: {

    },
    actions: {
        async loadAllProducts() {
            const ret = await getProducts()
            // 是  this.all 出现的 ts 类型问题
            this.all = ret
        },

        decrementProduct(product: IProduct) {
            const ret = this.all.find(item => item.id === product.id)
            if (ret) {
                ret.inventory--
            }
        }

    }
})

 在 components 中 创建组件 :

ShoppingCart.vue  


<template>
    <div class="cart">
        <h1>你的购物车</h1>
        <p>
        <h4>请添加一些商品到购物车 :</h4>
        </p>
        <ul class="ul1">
            <li v-for="item in cartStore.cartProducts">商品名称:{{ item.title }} - 商品价格:{{ item.price }} X
                商品数量:{{ item.quantity }}</li>
        </ul>
        <p>商品总价:{{ cartStore.totalPrice }}</p>
        <p>
            <button @click="cartStore.checkout">结算</button>
        </p>
        <p v-show="cartStore.checkoutStatus">
            结算:{{ cartStore.checkoutStatus }}
        </p>
    </div>
</template>
<script lang="ts" setup>


import { useCartStore } from '../store/cart';
const cartStore = useCartStore()



</script>
<style>
.ul1 {
    padding: 50px 10px;
    border: 1px solid rgb(255, 0, 0);
}
</style>

ProductList.vue 

<template>
    <ul>
        <li v-for="item in productsStore.all">
            商品名称:{{ item.title }}<br>
            商品价格:{{ item.price }}<br>
            <button :disabled="!item.inventory" @click="cartStore.addProductCart(item)">添加到购物车</button>
        </li>
    </ul>
</template>
<script lang="ts" setup>
// 进行 pinia 拿到导出的数据    , 且数据可以进行其他的方法进行   解构  ,但是因为数据少所有不需要 解构
import { useProductsStore } from '../store/products'
import { useCartStore } from '../store/cart'


const productsStore = useProductsStore()
const cartStore = useCartStore()



// 加载所有数据
productsStore.loadAllProducts()
</script>
<style>
ul {
    list-style-type: none;
    font-weight: 700;
    font-size: 25px;
}
</style>

 在src中创建   api  在里面创建 shop.ts:

export interface IProduct {
    id: number,
    title: string,
    price: number,
    inventory: number //库存数量
}


const _products: IProduct[] = [
    { id: 1, title: '苹果', price: 8888.01, inventory: 2 },
    { id: 2, title: '华为', price: 5666.99, inventory: 10 },
    { id: 3, title: '小米', price: 4999.99, inventory: 5 }
]

// 模拟异步效果
export const getProducts = async () => {
    await wait(100) // 加的延迟
    return _products
}
export const buyProducts = async () => {
    await wait(100) // 订单结算的延迟  ,模拟异步操作
    return Math.random() > 0.5
}

// 封装了 Promise 版本的定时器   wait   
async function wait(delay: number) {
    return new Promise((resolve) => setTimeout(resolve, delay))
}

然后就完成了  启动就好   npm run serve   

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue3是Vue.js的下一个主要版本,它引入了一些功能和改进,以提高性能和开发体验。而TypeScriptTS)是一种强类型的JavaScript扩展,它添加了静态类型检查等功能。Pinia是一个以Composition API为基础的状态管理库,它与Vue3紧密集成在一起。而Vite是一种快速的构建工具,特别适用于Vue3的开发和构建。 在具体实现登录功能时,可以按照以下步骤进行: 1. 首先,需要安装Vue3、TypeScript、Pinia和Vite。可以通过npm或yarn等包管理工具进行安装。 2. 创建一个新的Vue3项目,并设置使用TypeScript。 3. 在项目的入口文件中引入Vue、Pinia和创建Pinia实例。 4. 在Pinia实例中定义一个用于存储登录信息的状态。 5. 创建一个登录组件,在组件中定义一个表单,用于输入用户名和密码。 6. 在组件中引入定义好的Pinia实例,并使用`useStore`函数获取存储登录信息的状态。 7. 在组件的`methods`中,编处理登录功能的方法,验证用户名和密码是否正确。 8. 在组件的模板中,使用v-model指令将输入框与组件内的数据绑定,并绑定登录按钮的点击事件。 9. 在App组件中引入登录组件,并将其渲染到页面上。 10. 运行项目,在浏览器中打开页面,即可看到登录表单。 11. 输入正确的用户名和密码,点击登录按钮,触发登录方法,根据验证结果显示相应的提示信息。 通过以上步骤,可以实现一个基本的登录功能。使用Vue3、TypeScript、Pinia和Vite可以让开发过程更加高效和可靠。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值