Vue 開発の実践: レスポンシブな e コマース プラットフォームの構築

WBOY
リリース: 2023-11-03 08:22:46
オリジナル
1092 人が閲覧しました

Vue 開発の実践: レスポンシブな e コマース プラットフォームの構築

Vue は、Web 開発で広く使用されている人気のある JavaScript フレームワークです。この記事では、Vue を使用してレスポンシブな電子商取引プラットフォームを構築する方法を紹介します。 Vue を使用してフロントエンド インターフェイスを構築し、バックエンド API インターフェイスを呼び出してデータを取得します。また、Vue の応答メカニズムを使用して、データの自動更新と動的なレンダリングを実現します。ここでは、Vue の基礎知識、電子商取引プラットフォームの設計と実装の手順を紹介します。

1. Vue の基礎知識

1.1 Vue のインストールと使用方法

Vue は、CDN 参照またはインストール パッケージを直接ダウンロードして使用できます。ここでは、公式に提供されている Vue CLI ビルド ツールを使用して、Vue プロジェクトを迅速にビルドします。

Vue CLI をグローバルにインストールする:

npm install -g vue-cli
ログイン後にコピー

Vue CLI を使用して新しい Vue プロジェクトを作成する:

vue create my-project
ログイン後にコピー

1.2 Vue のコンポーネントベースの開発

Vue 考え方はコンポーネント開発であり、Vue アプリケーションは複数のコンポーネントで構成できます。各コンポーネントには、テンプレート、ビジネス ロジック、スタイルを含めることができます。コンポーネントは相互にネストしてデータを渡し、複雑なページ構造を形成できます。

以下は簡単な Vue コンポーネントの例です:

<template>
  <div>
    <h1>{{ title }}</h1>
    <ul>
      <li v-for="item in items">{{ item }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'MyComponent',
  props: {
    title: String,
    items: Array
  }
}
</script>

<style>
h1 {
  color: #333;
}
li {
  color: #666;
}
</style>
ログイン後にコピー

上記のコードは、タイトルとリストを含む MyComponent という名前のコンポーネントを定義します。コンポーネントは props 属性を通じて親コンポーネント データを渡すことができます。ここでは、title 属性と items 属性が使用されます。

1.3 Vue のイベント バインディングとトリガー

Vue のイベント バインディングとトリガーは他のフレームワークと似ており、v-on ディレクティブを通じてイベントをバインドし、$emit メソッドを通じてイベントをトリガーできます。イベントはパラメータとデータを渡すことができます。

次は、単純なイベント バインディングとトリガーの例です:

<template>
  <div>
    <button v-on:click="handleClick">Click me</button>
  </div>
</template>

<script>
export default {
  methods: {
    handleClick() {
      this.$emit('custom-event', 'Hello, world!')
    }
  }
}
</script>
ログイン後にコピー

上記のコードは、handleClick という名前のメソッドを定義します。これは、ボタンがクリックされたときにカスタム イベント イベントをトリガーし、文字を渡します。 . 文字列パラメータ。

2. eコマースプラットフォームの設計

eコマースプラットフォームには通常、商品の表示、ショッピングカート、注文確認、支払いなどの機能が含まれています。これらの機能に基づいて、次のページを含むシンプルな電子商取引プラットフォームを設計します。

  • ホーム ページ: すべての製品情報を表示し、検索と分類をサポートします。
  • 商品詳細ページ: 1 つの商品の詳細情報を表示し、ショッピング カートへの追加をサポートします。
  • ショッピング カート ページ: ショッピング カートに追加されたすべての商品情報が表示され、清算および決済操作がサポートされます。
  • 注文確認ページ: 選択したすべての製品情報が表示され、住所や支払い方法などの情報の入力がサポートされます。
  • 注文成功ページ: 注文の詳細が表示され、ホームページに戻ることができます。

デモンストレーションの便宜上、axios でシミュレートされた静的データと API インターフェイスのみを提供します。バックエンド データは JSON 形式を使用し、すべての製品情報と注文情報が含まれます。

3. 電子商取引プラットフォームの実装手順

3.1 ホームページ

ホームページにはすべての製品情報が表示され、検索と分類がサポートされます。ページのスタイルとアイコンを美しくするために、Bootstrap ライブラリと FontAwesome ライブラリを使用します。

npm install bootstrap font-awesome --save
ログイン後にコピー

まず、次の 2 つのライブラリをインストールします。

<template>
  <div>
    <nav class="navbar navbar-dark bg-dark">
      <a class="navbar-brand" href="#">电商平台</a>
    </nav>
    <div class="container mt-4">
      <router-view></router-view>
    </div>
  </div>
</template>

<style>
@import "bootstrap/dist/css/bootstrap.min.css";
@import "font-awesome/css/font-awesome.min.css";
</style>
ログイン後にコピー

App.vue ファイルにスタイル参照を追加します。

import Vue from 'vue'
import App from './App.vue'
import router from './router'

Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App),
}).$mount('#app')
ログイン後にコピー

Vue Router を使用して、ページ ジャンプを実装し、パラメーターを渡します。次のコードを main.js ファイルに追加します。

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from './views/Home.vue'

Vue.use(VueRouter)

export default new VueRouter({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    }
  ]
})
ログイン後にコピー

ルーティング構成を定義するための router.js ファイルを作成します。

<template>
  <div>
    <div class="input-group mb-4">
      <input type="text" class="form-control" v-model="searchText" placeholder="Search...">
      <div class="input-group-append">
        <button class="btn btn-outline-secondary" type="button" v-on:click="search">Search</button>
      </div>
    </div>
    <div class="row">
      <div class="col-md-4 mb-4" v-for="product in products" :key="product.id">
        <div class="card">
          <img class="card-img-top" :src="product.image" alt="Card image cap">
          <div class="card-body">
            <h5 class="card-title">{{ product.name }}</h5>
            <p class="card-text">{{ product.description }}</p>
            <p class="card-text font-weight-bold text-danger">{{ product.price }}</p>
            <button class="btn btn-primary" v-on:click="addToCart(product)">加入购物车</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      products: [],
      searchText: ''
    }
  },
  created() {
    this.getProducts()
  },
  methods: {
    getProducts() {
      axios.get('/api/products').then(response => {
        this.products = response.data
      })
    },
    search() {
      axios.get('/api/products', {
        params: {
          search: this.searchText
        }
      }).then(response => {
        this.products = response.data
      })
    },
    addToCart(product) {
      this.$emit('add-to-cart', product)
    }
  }
}
</script>
ログイン後にコピー

ホームページの表示および検索機能を実装するために Home.vue ファイルを作成します。

<template>
  <div>
    <div class="row mt-4">
      <div class="col-md-6">
        <img :src="product.image" class="img-fluid" alt="">
      </div>
      <div class="col-md-6">
        <h2>{{ product.name }}</h2>
        <p>{{ product.description }}</p>
        <p class="font-weight-bold text-danger">{{ product.price }}</p>
        <button class="btn btn-primary btn-lg" v-on:click="addToCart(product)">加入购物车</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      product: {}
    }
  },
  created() {
    const productId = this.$route.params.id
    axios.get(`/api/products/${productId}`).then(response => {
      this.product = response.data
    })
  },
  methods: {
    addToCart(product) {
      this.$emit('add-to-cart', product)
    }
  }
}
</script>
ログイン後にコピー

上記のコードは、axios を介して API インターフェイスを呼び出して製品情報を取得し、検索とショッピング カートへの追加操作をサポートします。

3.2 製品詳細ページ

製品詳細ページには、単一の製品の詳細情報が表示され、ショッピング カートへの追加がサポートされます。 Vue Router を使用して製品 ID パラメータを渡します。

Product.vue ファイルを作成して製品詳細ページを実装します。

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from './views/Home.vue'
import Product from './views/Product.vue'

Vue.use(VueRouter)

export default new VueRouter({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    {
      path: '/product/:id',
      name: 'product',
      component: Product
    }
  ]
})
ログイン後にコピー

Vue Router を使用して製品 ID パラメーターを渡します。 router.js 設定ファイルを変更します。

npm install vuex --save
ログイン後にコピー

3.3 ショッピング カート ページ

ショッピング カート ページには、ショッピング カートに追加されたすべての製品情報が表示され、清算および決済操作がサポートされます。状態管理とデータ共有には Vuex を使用します。

Vuex ライブラリをインストールします:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cart: []
  },
  mutations: {
    addToCart(state, product) {
      const item = state.cart.find(item => item.id === product.id)
      if (item) {
        item.quantity++
      } else {
        state.cart.push({
          ...product,
          quantity: 1
        })
      }
    },
    removeFromCart(state, productId) {
      state.cart = state.cart.filter(item => item.id !== productId)
    },
    clearCart(state) {
      state.cart = []
    }
  },
  getters: {
    cartTotal(state) {
      return state.cart.reduce((total, item) => {
        return total + item.quantity
      }, 0)
    },
    cartSubtotal(state) {
      return state.cart.reduce((total, item) => {
        return total + item.price * item.quantity
      }, 0)
    }
  }
})
ログイン後にコピー

Vuex の状態管理を構成するための store.js ファイルを作成します:

<template>
  <div>
    <nav class="navbar navbar-dark bg-dark">
      <a class="navbar-brand" href="#">电商平台</a>
      <span class="badge badge-pill badge-primary">{{ cartTotal }}</span>
    </nav>
    <div class="container mt-4">
      <router-view :cart="cart" v-on:add-to-cart="addToCart"></router-view>
    </div>
    <div class="modal" tabindex="-1" role="dialog" v-if="cart.length > 0">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">购物车</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <table class="table">
              <thead>
                <tr>
                  <th>名称</th>
                  <th>单价</th>
                  <th>数量</th>
                  <th>小计</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="item in cart" :key="item.id">
                  <td>{{ item.name }}</td>
                  <td>{{ item.price }}</td>
                  <td>
                    <button class="btn btn-sm btn-danger" v-on:click="removeFromCart(item.id)">-</button>
                    {{ item.quantity }}
                    <button class="btn btn-sm btn-success" v-on:click="addToCart(item)">+</button>
                  </td>
                  <td>{{ item.price * item.quantity }}</td>
                  <td><i class="fa fa-remove text-danger" v-on:click="removeFromCart(item.id)"></i></td>
                </tr>
              </tbody>
              <tfoot>
                <tr>
                  <td colspan="2">共 {{ cartTotal }} 件商品</td>
                  <td colspan="2">总计 {{ cartSubtotal }}</td>
                  <td><button class="btn btn-sm btn-danger" v-on:click="clearCart()">清空购物车</button></td>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import store from './store'

export default {
  computed: {
    cart() {
      return store.state.cart
    },
    cartTotal() {
      return store.getters.cartTotal
    }
  },
  methods: {
    addToCart(product) {
      store.commit('addToCart', product)
    },
    removeFromCart(productId) {
      store.commit('removeFromCart', productId)
    },
    clearCart() {
      store.commit('clearCart')
    }
  }
}
</script>
ログイン後にコピー

App.vue のコードを変更して状態を構成しますVuex の管理:

<template>
  <div>
    <h2>确认订单</h2>
    <table class="table">
      <thead>
        <tr>
          <th>名称</th>
          <th>单价</th>
          <th>数量</th>
          <th>小计</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in cart" :key="item.id">
          <td>{{ item.name }}</td>
          <td>{{ item.price }}</td>
          <td>{{ item.quantity }}</td>
          <td>{{ item.price * item.quantity }}</td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td colspan="2">共 {{ cartTotal }} 件商品</td>
          <td colspan="2">总计 {{ cartSubtotal }}</td>
        </tr>
      </tfoot>
    </table>
    <div class="form-group">
      <label for="name">姓名</label>
      <input type="text" class="form-control" id="name" v-model="name">
    </div>
    <div class="form-group">
      <label for="address">地址</label>
      <textarea class="form-control" id="address" v-model="address"></textarea>
    </div>
    <div class="form-group">
      <label for="payment">支付方式</label>
      <select class="form-control" id="payment" v-model="payment">
        <option value="alipay">支付宝</option>
        <option value="wechatpay">微信支付</option>
        <option value="creditcard">信用卡</option>
      </select>
    </div>
    <button class="btn btn-primary btn-lg" v-on:click="checkout">提交订单</button>
  </div>
</template>

<script>
export default {
  props: ['cartTotal', 'cartSubtotal'],
  data() {
    return {
      name: '',
      address: '',
      payment: 'alipay'
    }
  },
  methods: {
    checkout() {
      this.$router.push({
        name: 'order-success',
        params: {
          name: this.name,
          address: this.address,
          payment: this.payment,
          cart: this.$props.cart,
          cartTotal: this.cartTotal,
          cartSubtotal: this.cartSubtotal
        }
      })
    }
  }
}
</script>
ログイン後にコピー

上記のコードは、Vuex を使用して、ショッピング カートの追加、削除、クリア、計算の機能を実装します。

3.4 注文確認ページと注文成功ページ

注文確認ページには、選択したすべての製品情報が表示され、住所や支払い方法などの情報の入力がサポートされます。注文成功ページには注文の詳細が表示され、ホームページに戻ることができます。 Vue Router を使用して注文情報パラメータを渡します。

Cart.vue ファイルを作成して注文確認ページを実装します:

<template>
  <div>
    <h2>订单详情</h2>
    <p>姓名:{{ name }}</p>
    <p>地址:{{ address }}</p>
    <p>支付方式:{{ payment }}</p>
    <table class="table">
      <thead>
        <tr>
          <th>名称</th>
          <th>单价</th>
          <th>数量</th>
          <th>小计</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in cart" :key="item.id">
          <td>{{ item.name }}</td>
          <td>{{ item.price }}</td>
          <td>{{ item.quantity }}</td>
          <td>{{ item.price * item.quantity }}</td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td colspan="2">共 {{ cartTotal }} 件商品</td>
          <td colspan="2">总计 {{ cartSubtotal }}</td>
        </tr>
      </tfoot>
    </table>
    <button class="btn btn-primary btn-lg" v-on:click="backHome">返回首页</button>
  </div>
</template>

<script>
export default {
  props: ['name', 'address', 'payment', 'cart', 'cartTotal', 'cartSubtotal'],
  methods: {
    backHome() {
      this.$router.push('/')
    }
  }
}
</script>
ログイン後にコピー

OrderSuccess.vue ファイルを作成して注文成功ページを実装します:

import Vue from 'vue'
ログイン後にコピー

Vue Router を使用して、注文情報パラメータを渡します。 router.js の設定ファイルを変更します:

rrreee

以上がVue 開発の実践: レスポンシブな e コマース プラットフォームの構築の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!