vite搭建vue2項目的實戰(zhàn)過程
問題提出
最近在做一個練習的小項目,由于要配合組成員的其它成員來搭建項目,大多掌握的技術棧都在vue2,用慣了vite來搭建(vite真香~),就想著來搭建一個vue2的項目。原本以為查下百度很快可以搭好,沒想到折騰了一早上。。。。
??文章結尾會給出我的package.json文件
搭建過程
1、初始化項目
vite提供了對應的npm命令可以創(chuàng)建各種框架的項目,但是vite在創(chuàng)建vue項目時,默認直接創(chuàng)建vue3,因此這里我們使用原生項目進行創(chuàng)建
1.1 創(chuàng)建項目
注意:這里vite的版本采用2.8.0的,最新的版本創(chuàng)建后續(xù)會出現(xiàn)問題
npm init vite@2.8.0
后續(xù),安裝如圖
創(chuàng)建好項目后
// 1.進入項目 cd vite-vue2 // 2.安裝依賴 npm install // 3.啟動項目 npm run dev
效果圖如下:
1.2 安裝vite對vue2支持的插件
在vite-vue2安裝:vite-plugin-vue2
// 注意:vite-plugin-vue2的版本為1.9.3 npm install vite-plugin-vue2@1.9.3 -D
在根目錄創(chuàng)建vite.config.js文件,來注冊插件
import { defineConfig } from 'vite' // 動態(tài)配置函數(shù) import { createVuePlugin } from 'vite-plugin-vue2' import { resolve } from 'path' export default () => defineConfig({ plugins: [createVuePlugin()], server: { open: true, //自動打開瀏覽器 port: 1567 //端口號 }, resolve: { // 別名 alias: [ { find: '@', replacement: '/src' } ] } })
1.3 安裝vue依賴
npm命令安裝
寫本文時,通過npm install vue安裝會直接安裝3.0版本的因此要指定好vue版本
npm install vue@2.x vue-template-compiler@2.x -S
1.4 修改項目文件結構
1.4.1 創(chuàng)建src目錄
在項目根目錄下創(chuàng)建src
目錄,然后把main.js
移到src目錄里
import Vue from 'vue' import App from './App.vue' new Vue({ render: h => h(App) }).$mount('#app')
1.4.2 修改index.html
修改項目啟動的入口文件
// index.html <script type="module" src="/src/main.js"></script>
1.4.3 創(chuàng)建App.vue文件
代碼如下:
<template> <div>Hello Vite Vue2</div> </template>
1.5 運行一下項目
再次運行下項目檢驗一下之前配置有無問題
npm run dev
2、vue-router
2.1 安裝
npm install vue-router@3.5.2 -S
2.2 新建router目錄
2.2.1 創(chuàng)建路由表
在src目錄下創(chuàng)建router目錄,并在router目錄下創(chuàng)建index.js文件和module目錄,在module目錄下創(chuàng)建home.js和index.js。這里采用分模塊來存放路由表
// /src/router/module/home.js export const home = [ { path: '/home', meta: { title: '首頁' }, component: () => import('@/views/home/Index.vue') } ]
// /src/router/module/index.js import { home } from './home' export const module = [...home]
// /src/router下index.js import { module } from './module/index' import VueRouter from 'vue-router' import Vue from 'vue' // 使用VueRouter Vue.use(VueRouter) const routes = [ ...module ] const router = new VueRouter({ mode: 'history', base: '/', routes }) export default router
2.2.2 創(chuàng)建路由指向的頁面組件
在 src
目錄下創(chuàng)建 views
目錄,用來存放頁面組件。
在 src/views/home
目錄下創(chuàng)建1個頁面:Index.vue
<template> <div> Home </div> </template>
2.3 全局注冊
2.3.1 在main.js里注冊
import Vue from 'vue' import App from './App.vue' import router from './router/index.js' new Vue({ router, render: h => h(App) }).$mount('#app')
2.3.2 創(chuàng)建路由跳轉標簽
修改App.vue文件
<template> <div id="app" class="app"> <router-view></router-view> </div> </template>
3、vuex
vuex作為大型單頁面的狀態(tài)管理器,使用起來十分方便,在有mapState、mapMutation等語法糖的引入變得更加的簡單,但當項目比較小的時候可以不引入,可能會變得臃腫起來,這里為了學習就引入進來了~
3.1 安裝
npm install vuex@3.6.2 -S
3.2 新建vuex目錄
在src
目錄下創(chuàng)建store
目錄,并在store
目錄下創(chuàng)建index.js
// index.js import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) // 使用Vuex export default new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++ } }, actions: {}, modules: {} })
3.3 全局注冊
import Vue from 'vue' import App from './App.vue' import router from './router/index.js' import store from './store' new Vue({ router, store, render: h => h(App) }).$mount('#app')
4、組件庫
這里組件庫我采用了阿里推薦的ant-design-vue,版本采用1.x才兼容vue2
4.1 安裝
npm install ant-design-vue@1.7.8 -S
4.2 按需引入
ps:在官網看半天還以為要引入babel-plugin-import 來按需引入,搞半天最后發(fā)現(xiàn)可以直接引入。。。。
在src建立目錄plugin/antd
目錄,在下面創(chuàng)建index.js文件,代碼如下:
import Vue from 'vue' import { Button, message } from 'ant-design-vue' // 按需引入 import 'ant-design-vue/dist/antd.css' // or 'ant-design-vue/dist/antd.less' // 掛載全局Message Vue.prototype.$message = message Vue.use(Button)
4.3 在main.js全局注冊
// main.js // 引入antd import './plugin/antd' new Vue({ router, store, render: h => h(App) }).$mount('#app')
4.4 在頁面中使用
<template> <div> <a-button type="dashed" @click="onClick"> Dashed </a-button> </div> </template> <script> export default { mounted() { }, methods: { onClick() { this.$message.info('This is a normal message'); } } } </script>
5、axios
本文會對axios做一個簡單的封裝。
5.1 安裝
npm install axios -S
5.2 封裝axios
在src創(chuàng)建http目錄,在其下面創(chuàng)建request.js
和home.js
// request.js import axios from 'axios' import { message } from 'ant-design-vue' // 創(chuàng)建axios實例 // 創(chuàng)建請求時可以用的配置選項 // 配后端數(shù)據的接收方式application/json;charset=UTF-8或者application/x-www-form-urlencoded;charset=UTF-8 const contentType = 'application/json;charset=UTF-8' const instance = axios.create({ /** * 是否攜帶cookie,注意若攜帶cookie后端必須配置 * 1.Access-Control-Allow-Origin為單一域名(具體到IP + port,用localhost貌似不行) * 2.需要帶上響應頭Access-Control-Allow-Credentials */ // withCredentials: true, timeout: 1000, baseURL: 'http://localhost:8000/api/v1', headers: { 'Content-Type': contentType } }) // axios的全局配置 instance.defaults.headers.post = { 'Content-Type': 'application/x-www-form-urlencoded' } instance.defaults.headers.common = { 'Auth-Type': 'company-web', 'X-Requested-With': 'XMLHttpRequest', token: 'sdfjlsdfjlsdjflsjflsfjlskd' } // 添加請求攔截器(post只能接受字符串類型數(shù)據) instance.interceptors.request.use( config => { const token = window.sessionStorage.getItem('token') if (token) { config.headers.Authorization = token } return config }, error => { return Promise.reject(error) } ) const errorHandle = (status, other) => { switch (status) { case 400: message.error('信息校驗失敗') break case 401: // @ts-nocheck message.error('認證失敗') break case 403: message.error('token校驗失敗') break case 404: message.error('請求的資源不存在') break default: message.error(other) break } } // 添加響應攔截器 instance.interceptors.response.use( // 響應包含以下信息data,status,statusText,headers,config res => { if (res.data && res.data.code !== 0 && !(res.data instanceof Blob)) { message.error(res.data.msg || '服務器出錯!') } // 請求通用處理 return res.data }, err => { // message.error(err) const { response } = err if (response) { errorHandle(response.status, response.data) return Promise.reject(response) } message.error('請求失敗') return true } ) export default instance
import request from './request' export default { getList(model) { return request({ url: '/theme/list', method: 'post', data: model }) }, }
5.3 在頁面中使用
<script> import $http from '@/http/home.js' export default { mounted() { }, methods: { async onSubmit(){ const res = await $http.getList({}); console.log(res) } } } </script>
總結
以上就是我用vite搭建vue2項目的一個全過程啦。希望對大家搭建項目有所幫助,如果有幫助的話,歡迎給文章點個贊??也歡迎留言提問?
??最后的最后,附上我的package.json
文件(這點真的很重要??)
{ "name": "vite-vue2", "private": true, "version": "0.0.0", "scripts": { "dev": "vite", "build": "vite build", "preview": "vite preview" }, "devDependencies": { "less": "^3.9.0", "less-loader": "^4.1.0", "vite": "^2.8.0", "vite-plugin-vue2": "^1.9.3" }, "dependencies": { "ant-design-vue": "^1.7.8", "axios": "^0.27.2", "qs": "^6.11.0", "vue": "^2.7.8", "vue-router": "^3.5.2", "vue-template-compiler": "^2.7.8", "vuex": "^3.6.2" } }
9.16更新
感謝評論區(qū)網頁的提問意見。解決了兩個問題
安裝vue-router時應該是npm install vue-router@3.5.2 -S
使用npm run build
之后用npm run preview
會出現(xiàn)require is not defined的問題。這個可以參考這篇文章vue cli改造vite最佳實踐。注意:經過實踐,本項目出現(xiàn)的根源在于組件庫ant-design-vue的問題,這里需要在vite.config.js
加入如下的配置:
resolve: { alias: [ // 忽略其他代碼 { find: /ant-design-vue$/, replacement: 'ant-design-vue/dist/antd.min' } // 解決關鍵點。 ] },
參考資料
到此這篇關于vite搭建vue2項目的文章就介紹到這了,更多相關vite搭建vue2項目內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue @click與@click.native,及vue事件機制的使用分析
這篇文章主要介紹了vue @click與@click.native,及vue事件機制的使用分析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04VUE如何實現(xiàn)點擊文字添加顏色(動態(tài)修改class)
這篇文章主要介紹了VUE如何實現(xiàn)點擊文字添加顏色(動態(tài)修改class),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11