vite+vue3.0项目搭建

1 项目初始化

    npm init vite-app <project-name>
    cd <project-name>
    npm install
    npm run dev
 

运行完以上命令之后,一个vue3.0的项目就可以了,目录如下:

image.png

那么接下来我们就参照vue2.x的全家桶来从零填充一下项目基础模块:

1. vite.config.js(等同于vue.config.js)配置一些服务配置以及打包配置
2. vuex4.0状态管理,管理全局状态
3. vue-router引入
4. axios处理xhr请求的配置,缺省配置,以及请求拦截
5. 引入UI框架并设置一些常用主题配置
 

2 vite.config.js配置

const path = require('path')
// vite.config.js # or vite.config.ts

module.exports = {
  // 引入第三方的配置 会将引入的第三方文件移动到E: \gitcode\gitcode\工程目录\gitcode\工程目录\node_modules\gitcode\工程目录\node_modules\.vite_opt_cache目录中
  optimizeDeps: {
    include: []
  },
  alias: {
    // 键必须以斜线开始和结束
    '/@/': path.resolve(__dirname, './src')
  },
  //   hostname: '0.0.0.0',
  port: 8080,
  // 是否自动在浏览器打开
  open: true,
  // 是否开启 https
  https: false,
  // 服务端渲染
  ssr: false,
  /**
   * 在生产中服务时的基本公共路径。
   * @default '/'
   */
  base: './',
  /**
   * 与“根”相关的目录,构建输出将放在其中。如果目录存在,它将在构建之前被删除。
   * @default 'dist'
   */
  outDir: 'dist',
  // 反向代理
  proxy: {
    '/api': {
      target: 'https://blog.csdn.net/weixin_45292658',
      changeOrigin: true,
      rewrite: path => path.replace(/^\/api/, '')
    }
  }
}

 

3. vuex4.x的引入

  • 安装
npm install vuex@next --save
 
  • 创建目录

image.png

  • index.js
import { createStore } from 'vuex'
import getters from './getters'
import app from './modules/app'
import user from './modules/user'

// 创建 store 容器实例.
const store = createStore({
modules: {
 app,
 user
},
getters
})

export default store

 
  • getters.js
const getters = {
projectTitle: state => state.app.projectTitle,
userName: state => state.user.userName,
userId: state => state.user.userId
}
export default getters

 
  • user.js
const user = {
state: {
 userName: '',
 userId: ''
},
// commit('user/setUserInfo')
mutations: {
 setUserInfo (state, { userName, userId }) {
   // `state` is the local module state
   state.userName = userName
   state.userId = userId
 }
},
// dispatch('user/setUserInfo')
actions: {
 setUserInfo ({ commit }, userInfo) {
   commit('setUserInfo', userInfo)
 }
}
}
export default user


 
  • main.js
import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
import store from '/@/store'
// vue2.x用法
store.dispatch('setUserInfo', {
userName: '付太平',
userId: 12333
})
console.log(store.getters.userName)
console.log(store.getters.userId)
createApp(App)
.use(store)
.mount('#app')

 
  • vue3.x用法
<template>
<h1>{{ msg }}</h1>
<button @click="count++">count is: {{ count }}</button>
<button @click="updateUserInfo">更新用户信息</button>
<button @click="resetUserInfo">重置用户信息</button>
<div>
 <p>userName: {{ userName }}</p>
 <p>userId: {{ userId }}</p>
</div>
</template>

<script>
import { useStore } from 'vuex'
import { ref, computed } from 'vue'
export default {
name: 'HelloWorld',
props: {
 msg: String
},
setup () {
 const store = useStore()
 let count = ref(0)
 // 获取store的默认值
 let userName = computed(() => store.getters.userName)
 let userId = computed(() => store.getters.userId)
 // 更新store数据
 const resetUserInfo = () => {
   // access a mutation
   store.commit('setUserInfo', { userName: '付太平', userId: 123 })
 }
 const updateUserInfo = () => {
   // access an action
   store.dispatch('setUserInfo', { userName: 'admin', userId: 321 })
 }

 return {
   count,
   userName,
   userId,
   resetUserInfo,
   updateUserInfo
 }
}
}
</script>

 

4 vue-router引入

  • 安装
npm install vue-router@4
 
  • 创建目录

image.png

  • index.js
import { createRouter, createWebHashHistory } from 'vue-router'
import home from '/@/view/home/index.vue'
import login from '/@/view/login/index.vue'
const routes = [
  {
    path: '/home',
    name: 'home',
    component: home
  },
  {
    path: '/login',
    name: 'login',
    component: login
  }
]
const router = createRouter({
  history: createWebHashHistory(),
  routes
})
export default router

 
  • main.js
import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
import store from '/@/store'
import router from './router'
createApp(App)
  .use(store)
  .use(router)
  .mount('#app')

 

综合以上router的使用就可以了,当然一般项目都会有嵌套路由以及布局组件,路由守卫权限认证这里就不概述了!

  • axios引入
  1. 安装
npm install axios --save     
 
  1. 创建request.js封装请求
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

service.interceptors.request.use(
  config => {
    //  ToDo 这里获取用户登录的token并设置自定义请求头
    return config
  },
  error => {
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 20000) {
      ElMessage({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        ElMessageBox.confirm(
          '你已被登出, 可以取消继续留在该页面,或者重新登录',
          '确定登出',
          {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          location.reload()
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return response.data
    }
  },
  error => {
    ElMessage({
      message: error.messa,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

 
  1. 创建api目录,编写api接口
import request from '../utils/request.js'
export const loginApi = data => {
  return request({
    url: '/api/bidingDetail/searchSingleBidingDetailApprove',
    method: 'post',
    data: data
  })
}

 

5 引入UI框架elementUi-plus

  • 安装
 npm install element-plus --save
 
  • main.js中全局引用
import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
import store from '/@/store'
import router from './router'
import ElementPlus from 'element-plus'
import 'element-plus/lib/theme-chalk/index.css'
createApp(App)
  .use(ElementPlus)
  .use(store)
  .use(router)
  .mount('#app')

 
  • 在组件中使用
<template>
  <h3>this is home's page</h3>
  <HelloWorld msg="Hello Vue 3.0 + Vite" />
  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="date" label="日期" width="180"> </el-table-column>
    <el-table-column prop="name" label="姓名" width="180"> </el-table-column>
    <el-table-column prop="address" label="地址"> </el-table-column>
  </el-table>
</template>
<script>
import { reactive } from 'vue'
import HelloWorld from '/@/components/HelloWorld.vue'
export default {
  name: 'home',
  setup () {
    let tableData = reactive([
      {
        date: '2016-05-02',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1518 弄'
      },
      {
        date: '2016-05-04',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1517 弄'
      },
      {
        date: '2016-05-01',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1519 弄'
      },
      {
        date: '2016-05-03',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1516 弄'
      }
    ])
    return {
      tableData
    }
  },
  components: {
    HelloWorld
  }
}
</script>

 

image.png
经过以上的操作,一个前端项目架子基本已经搭建起来了,当然运用到实际项目中还有很多东西没有完善,这篇文章就不一一列举了。在引入UI框架的时候遇到了一个问题,如果项目目录存在中文名称会导致UI的样式引入报错,这里需要注意下

原创文章,作者:我心飞翔,如若转载,请注明出处:https://www.pipipi.net/14691.html

发表评论

登录后才能评论