«

Vue实现的外卖首页

yang 发布于 阅读:373 Vue2阶段


首先,我们需要在Vue中安装一些依赖项。

npm install vue vue-router axios vant -S

Vue Router 和 Axios 用于进行页面路由和 HTTP 请求,Vant 是一个 UI 组件库,用于构建漂亮的界面。我们将使用它们来创建外卖首页。

首先,我们需要设置路由。在 src/router/index.js 文件中添加以下内容:

import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/views/Home.vue'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    }
  ]
})

这个文件将我们的主页组件绑定到根路径。

然后我们可以进入到 src/views/Home.vue 文件写主要的Home组件,代码如下:

<template>
  <div class="home">
    <div class="banner">
      <img src="./assets/banner.png" alt="banner" />
    </div>
    <van-search v-model="search" placeholder="请输入您的地址" />
    <div class="category">
      <div v-for="(item, index) in categories" :key="index" class="category-item">
        <img :src="item.icon" alt="icon" />
        <span>{{ item.title }}</span>
      </div>
    </div>
    <div class="list">
      <div class="list-item" v-for="(item, index) in items" :key="index">
        <img :src="item.image" alt="food" />
        <div class="title">{{ item.title }}</div>
        <div class="price">¥{{ item.price }}</div>
        <van-button type="info" size="small">加入购物车</van-button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'Home',
  data() {
    return {
      categories: [],
      items: [],
      search: ''
    }
  },
  created() {
    axios.get('/api/categories').then(response => {
      this.categories = response.data
    })

    axios.get('/api/items').then(response => {
      this.items = response.data
    })
  }
}
</script>

<style>
.banner {
  margin-bottom: 20px;
}

.category {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.category-item img {
  width: 60px;
  height: 60px;
  margin-bottom: 10px;
}

.list-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.list-item img {
  width: 120px;
  height: 120px;
  margin-bottom: 10px;
}

.title,
.price {
  margin-bottom: 10px;
}

.price {
  color: #f60;
}
</style>

这段代码将展示搜索框、分类列表和食品列表。其中,分类列表和食品列表的数据将通过 HTTP 请求从服务器端获取。

接下来,我们需要添加一些样式。在 src/App.vue 文件中,添加以下内容:

<template>
  <div id="app">
    <router-view />
  </div>
</template>

<style>
#app {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
</style>

这个样式设置了页面垂直居中。

现在,我们需要在 public/index.html 文件中添加以下内容,引入组件库的 CSS 文件:

<!-- 引入vant的样式文件 -->
<link rel="stylesheet" href="https://cdn.staticfile.org/vant/2.10.13/index.css" />

这样我们就完成了外卖首页的制作。现在,运行以下命令即可在浏览器中预览页面:

npm run serve

这就是一个外卖首页的实现。

Vue的外卖首页

版权所有:微4e
文章标题:Vue实现的外卖首页
除非注明,文章均为 微4e 原创,请勿用于任何商业用途,禁止转载

推荐阅读:


扫描二维码,在手机上阅读
请先 登录 再评论