用vue和node写的简易购物车实现

yizhihongxing

下面我将为大家介绍用Vue和Node.js写的简易购物车实现的完整攻略。

准备工作

环境要求

  • Node.js
  • Vue.js
  • 基本的HTML和CSS知识

项目结构

├── client # 前端代码
│   ├── node_modules # 依赖
│   ├── public # 静态资源
│   ├── src # 源代码
│   ├── .gitignore # git忽略文件配置
│   ├── package.json # 依赖配置
│   ├── package-lock.json # 依赖锁定
│   ├── README.md # 项目说明
│   └── yarn.lock # 依赖锁定
├── server # 后端代码
│   ├── node_modules # 依赖
│   ├── bin # 可执行文件
│   ├── config # 配置文件
│   ├── controllers # 控制器
│   ├── libs # 工具库
│   ├── models # 数据模型
│   ├── routes # 路由
│   ├── app.js # 入口文件
│   ├── .gitignore # git忽略文件配置
│   ├── package.json # 依赖配置
│   ├── package-lock.json # 依赖锁定
│   ├── README.md # 项目说明
│   └── yarn.lock # 依赖锁定
├── .gitignore # git忽略文件配置
└── README.md # 项目说明

开始构建

创建Vue应用

vue create client

安装ElementUI

cd client
yarn add element-ui -S

在main.js里面引入

import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App.vue';

Vue.use(ElementUI);

new Vue({
  render: (h) => h(App),
}).$mount('#app');

编写商品列表

<template>
  <el-table :data="products" style="width: 100%;">
    <el-table-column prop="name" label="商品名称"></el-table-column>
    <el-table-column prop="price" label="价格"></el-table-column>
    <el-table-column label="操作">
      <template slot-scope="scope">
        <el-button type="primary" @click="addToCart(scope.row)">加入购物车</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
export default {
  data() {
    return {
      products: [
        {
          name: '商品A',
          price: 10,
        },
        {
          name: '商品B',
          price: 20,
        },
      ],
    };
  },
  methods: {
    addToCart(product) {
      this.$emit('add-to-cart', product);
    },
  },
};
</script>

编写购物车列表

<template>
  <el-table :data="cart" style="width: 100%;">
    <el-table-column prop="name" label="商品名称"></el-table-column>
    <el-table-column prop="price" label="价格"></el-table-column>
    <el-table-column label="数量">
      <template slot-scope="scope">
        <el-input-number v-model="scope.row.quantity" :min="1"></el-input-number>
      </template>
    </el-table-column>
    <el-table-column label="总价">
      <template slot-scope="scope">
        {{ (scope.row.price * scope.row.quantity).toFixed(2) }}
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template slot-scope="scope">
        <el-button type="danger" @click="removeFromCart(scope.row)">移除</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
export default {
  props: {
    cart: {
      type: Array,
      default: () => [],
    },
  },
  methods: {
    removeFromCart(product) {
      this.$emit('remove-from-cart', product);
    },
  },
};
</script>

创建Node.js应用

mkdir server && cd server
npm init -y

安装Express

npm install express

安装MongoDB

brew install mongodb

在app.js里面添加以下内容

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const port = 3000;

// 连接数据库
mongoose.connect('mongodb://localhost/vue-shopping-cart', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

// 定义数据模型
const Product = mongoose.model('Product', {
  name: String,
  price: Number,
});

// 跨域配置
app.use(cors());

// 解析请求体
app.use(bodyParser.json());

// 获取商品列表
app.get('/api/products', async (req, res) => {
  const products = await Product.find();
  res.json(products);
});

// 生成订单
app.post('/api/orders', (req, res) => {
  console.log(req.body);
  res.send('Create order success.');
});

// 启动服务器
app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});

示例说明1:获取商品列表

在client里面的ProductList.vue里面添加以下代码

<script>
import axios from 'axios';

export default {
  data() {
    return {
      products: [],
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      axios.get('http://localhost:3000/api/products').then((res) => {
        this.products = res.data;
      });
    },
    addToCart(product) {
      const cart = JSON.parse(localStorage.getItem('cart')) || [];
      let item = cart.find((el) => el._id === product._id);

      if (!item) {
        item = {
          _id: product._id,
          name: product.name,
          price: product.price,
          quantity: 1,
        };
        cart.push(item);
      } else {
        item.quantity++;
      }

      localStorage.setItem('cart', JSON.stringify(cart));

      this.$emit('cart-updated', cart);
    },
  },
};
</script>

示例说明2:生成订单

在client里面的Checkout.vue里面添加以下代码

<script>
import axios from 'axios';

export default {
  data() {
    return {
      cart: [],
      order: {},
    };
  },
  created() {
    this.cart = JSON.parse(localStorage.getItem('cart')) || [];
  },
  computed: {
    total() {
      let sum = 0;

      this.cart.forEach((item) => {
        sum += item.price * item.quantity;
      });

      return sum.toFixed(2);
    },
  },
  methods: {
    submitOrder() {
      axios
        .post('http://localhost:3000/api/orders', {
          cart: this.cart,
          order: this.order,
          total: this.total,
        })
        .then((res) => {
          localStorage.removeItem('cart');
          this.cart = [];
          this.order = {};
          this.$message.success('订单创建成功!');
        });
    },
  },
};
</script>

代码演示

完整的代码可在以下仓库中查看:

你可以按照以下步骤运行代码:

  • 克隆仓库到本地

bash
git clone https://github.com/baykier/vue-shopping-cart.git

  • 进入client目录,安装依赖并启动前端应用

bash
cd vue-shopping-cart/client
yarn
yarn serve

  • 进入server目录,安装依赖并启动后端应用

bash
cd vue-shopping-cart/server
npm install
npm start

或者使用nodemon来启动

bash
nodemon bin/www

  • 打开浏览器,访问 http://localhost:8080/,开始使用购物车应用。

以上就是用Vue和Node.js写的简易购物车实现的完整攻略,希望能对大家有所帮助。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:用vue和node写的简易购物车实现 - Python技术站

(0)
上一篇 2023年6月8日
下一篇 2023年6月8日

相关文章

  • JS使用贪心算法解决找零问题示例

    首先,让我们了解一下什么是贪心算法。贪心算法(Greedy algorithm)在每一步选择中都采取在当前状态下最优的选择,从而希望导致结果是全局最优的算法。在找零钱的问题上,贪心算法指的是在找零过程中,每次选取最大的面额进行找零。以下是使用JS实现贪心算法解决找零问题的步骤: 排序 对于现金支付金额和硬币面额数组,我们可以先对硬币面额数组进行从大到小的排序…

    node js 2023年6月8日
    00
  • 吐槽一下我所了解的Node.js

    吐槽一下我所了解的Node.js 简介 Node.js 是一款基于 Chrome V8 引擎的 JavaScript 运行环境。它利用事件驱动、非阻塞I/O模型使其轻量且高效。Node.js 被广泛运用于构建 Web 应用、命令行工具等。 优点 强大的异步 I/O 处理能力 Node.js 利用事件循环机制,可以在单线程的情况下实现高并发。它的 I/O 库是…

    node js 2023年6月8日
    00
  • Node.js数据库钩子的使用

    Node.js是一个非常流行的服务器端运行时环境,可以使用它来构建高效的应用程序。在Node.js应用程序中,我们经常需要连接到数据库,并在数据库读取或写入数据时执行某些操作。Node.js提供了一种非常强大的技术 – 数据库钩子,可以用于在数据库读写操作的执行前或执行后自动执行某些特定的代码。 什么是数据库钩子 数据库钩子是一种让你在数据库执行查询或写入操…

    node js 2023年6月8日
    00
  • node.js调用C++函数的方法示例

    下面是关于 node.js 调用 C++ 函数的方法示例的完整攻略: 1. C++ 函数的编写 首先,我们需要编写一个 C++ 的函数,作为我们要在 node.js 中调用的方法。这个函数可以采用任何的 C++ 编写方式(使用指针、引用等),只要最终能够正确地返回我们需要的结果即可。 例如,我们编写了一个名为 add 的函数,用于将两个整数相加并返回它们的和…

    node js 2023年6月8日
    00
  • nodejs 如何手动实现服务器

    首先,我们需要了解一些基础知识,包括Node.js和HTTP协议的基本原理。 Node.js是一个使用JavaScript构建应用程序的平台。它使用事件驱动、非阻塞I/O模型,可以快速、高效地处理大量的并发连接。HTTP是一种基于请求和响应模式的协议,用于从web服务器传输超文本。 为了手动实现一个服务器,我们需要完成以下步骤: 引入http模块 我们使用N…

    node js 2023年6月8日
    00
  • 关于访问node express中的static静态文件方法

    访问node express中的static静态文件是一件非常常见的事情,下面是关于如何进行访问的完整攻略: 1. 在express中设置静态文件夹 要在Express应用程序中提供静态文件,我们需要使用express中的内置中间件express.static。该中间件可以将静态文件服务于公共目录,我们可以通过以下方式将其设置: const express …

    node js 2023年6月8日
    00
  • 在NPM发布自己造的轮子的方法步骤

    当我们完成了自己的JavaScript库或工具时,可能会希望将其发布到NPM,以便其他人可以使用它。下面是在NPM上发布自己的轮子的步骤。 1. 创建NPM账户 在使用NPM发布你的代码之前,你需要一个账户。如果你还没有NPM账户,可以通过在终端中键入以下命令来创建一个新账户: npm adduser 2. 在本地初始化你的项目 要在NPM上发布你的项目,你…

    node js 2023年6月8日
    00
  • Node.js返回JSONP详解

    一、什么是JSONP? JSONP是一种跨域访问数据的方式,它通过动态生成script标签,将请求发送到跨域地址上,跨域地址返回一段特定格式的JavaScript代码,调用一个回调函数,将数据作为参数传递给该函数。由于script标签不受同源策略的限制,因此可以轻松实现跨域请求数据的功能。 二、JSONP的实现原理 创建script标签,将请求发送至跨域地址…

    node js 2023年6月8日
    00
合作推广
合作推广
分享本页
返回顶部