自学内容网 自学内容网

uniapp-vue3-vite 搭建小程序、H5 项目模板

搭建一个使用 UniAppVue 3Vite 的小程序与 H5 项目模板相对简单,下面将详细介绍步骤,包括环境配置、项目创建、代码结构和基本示例。

环境准备

  1. Node.js:确保你已安装 Node.js(建议使用 LTS 版本)。可以通过以下命令检查 Node.js 和 npm 的版本:

    node -v
    npm -v
    
  2. Vite:全局安装 Vite(通常在项目创建时会自动安装):

    npm install -g create-vite
    
  3. UniApp:在安装了 HBuilderX 的情况下,也可以使用命令行工具。通过 npm 安装 @vue/cli

    npm install -g @vue/cli

创建项目

  1. 使用 Vite 创建 UniApp 项目: 在终端中,使用以下命令创建一个新的项目:

    npm create vite@latest my-uniapp-project --template vue
  2. 进入项目目录

    cd my-uniapp-project
  3. 安装 UniApp 和相关依赖: 安装 UniApp 相关的依赖包:

    npm install @dcloudio/uni-app
  4. 安装其他必要依赖

    npm install @dcloudio/uni-cli-shared @dcloudio/vue-cli-plugin-uni @dcloudio/uni-helper
    

配置项目

  1. 修改 package.json: 在 package.json 中,添加以下 scripts 用于编译和开发:

    {
      "scripts": {
        "dev": "vite",
        "build": "vite build"
      }
    }
    
  2. 添加 vite.config.js 文件: 在项目根目录下创建 vite.config.js 文件,配置 UniApp 支持:

    import { defineConfig } from 'vite';
    import vue from '@vitejs/plugin-vue';
    import uni from '@dcloudio/vite-plugin-uni';
    
    export default defineConfig({
      plugins: [vue(), uni()]
    });
    
  3. 创建项目结构: 在 src 目录下,创建以下文件和文件夹结构:

    ├── src
    │   ├── components       // 自定义组件
    │   ├── pages            // 页面
    │   │   ├── index.vue    // 首页
    │   │   └── about.vue     // 关于页
    │   ├── App.vue          // 根组件
    │   └── main.js          // 入口文件
    

示例代码

1. App.vue 文件
<template>
  <router-view />
</template>

<script>
export default {
  name: 'App',
};
</script>

<style>
/* 全局样式 */
</style>
2. index.vue 文件
<template>
  <view class="container">
    <text class="title">欢迎来到 UniApp + Vue 3 + Vite 项目!</text>
    <button @click="navigateToAbout">关于</button>
  </view>
</template>

<script>
export default {
  name: 'Index',
  methods: {
    navigateToAbout() {
      uni.navigateTo({
        url: '/pages/about/about'
      });
    }
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
}
.title {
  font-size: 20px;
  font-weight: bold;
}
</style>
3. about.vue 文件
<template>
  <view class="container">
    <text class="title">关于我们</text>
    <button @click="goBack">返回</button>
  </view>
</template>

<script>
export default {
  name: 'About',
  methods: {
    goBack() {
      uni.navigateBack();
    }
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
}
.title {
  font-size: 20px;
  font-weight: bold;
}
</style>

运行项目

  1. 启动开发服务器: 在终端中运行以下命令:

    npm run dev
  2. 打开浏览器: 访问 http://localhost:3000 进行开发测试。

构建项目

  1. 构建小程序和 H5 版本

    npm run build

    生成的构建文件将位于 dist 目录中。

注意事项

  • 使用 HBuilderX 进行小程序打包时,可以更方便地管理小程序的配置。
  • UniApp 的特性和API会有一些差异,确保在小程序和 H5 上进行测试。
  • 确保根据你的需求调整项目配置。

结论

通过以上步骤,你可以使用 UniAppVue 3Vite 创建一个基本的跨平台小程序和 H5 项目模板。


原文地址:https://blog.csdn.net/bollat/article/details/142929187

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!