赞
踩
本项目采用 vue3 + webpack 的方式来开发,已经引入了常用功能,不需要再去配置路由、请求、pinia 等,上手直接开发页面即可,真正做到开箱即用
你可以直接拉取我的仓库来直接使用,也可以按照本文教程自己操作
仓库地址:https://gitee.com/szxio/vue3-template。
如果对你有用的话,点赞、收藏、关注。❥(^_-)
npm install
npm run serve
npm run build
首先安装依赖,本项目已经安装好,下面只是教程
npm install pinia
新建 src/store/index.js
,内容如下
import {createPinia} from 'pinia'
export default createPinia()
在 main.js
中引入
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
import pinia from '@/store/index.js'
app.use(pinia)
app.mount('#app')
新建 src/store/userInfo.js
,内容如下
import { defineStore } from 'pinia'
// 第一个参数是应用程序中 store 的唯一 id
export const userInfo = defineStore('userInfo', {
state: () => ({
userInfo: {
name: 'lisi',
age: 18,
},
}),
actions: {
async setUserInfo(data) {
this.userInfo = data
},
},
})
在页面中使用
<template>
<div>
{{ store.userInfo.name }}
<button @click="getClick">修改store</button>
</div>
</template>
import { userInfo } from '@/store/userInfo'
const store = userInfo()
const getClick = () => {
store.setUserInfo({
name: 'wangwu',
})
}
npm install vue-i18n
新建 src/i18n/index.js
,内容如下
import { createI18n } from 'vue-i18n'
import homeEn from './home/en.js'
import homeZh from './home/zh.js'
const messages = {
en: {
home: { ...homeEn },
},
zh: {
home: { ...homeZh },
},
}
const language = (navigator.language || 'zh').toLocaleLowerCase() // 这是获取浏览器的语言
const i18n = createI18n({
legacy: false,
locale: localStorage.getItem('i18n') || language.split('-')[0] || 'zh', // 首先从缓存里拿,没有的话就用浏览器语言,
fallbackLocale: 'zh', // 设置备用语言
messages,
})
export default i18n
上面引入的中英文文件分别如下
src/i18n/home/en.js
export default {
login: 'Log in',
userName: 'Username',
password: 'Password',
}
src/i18n/home/zh.js
export default {
login: '登录',
userName: '用户名',
password: '密码',
}
在 main.js
文件中引入
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
import i18n from '@/i18n/index.js'
app.use(i18n)
app.mount('#app')
$t
不用在js中单独引入,在全局已经引入过了,所以这里在页面中可以直接使用
<template>
<div>
{{ $t('home.userName') }}
<el-button type="primary" @click="switchLanguage">切换语言</el-button>
</div>
</template>
<script setup>
const switchLanguage = () => {
localStorage.setItem('i18n', 'en')
window.location.reload()
}
</script>
这里不能安装高版本,否则会有兼容问题导致项目启动不起来
npm install sass sass-loader@8.0.2 node-sass@4.14.1
新建 src/assets/style/index.scss
:root {
--primary-color: #1c82e3;
}
body {
margin: 0;
min-height: 100vh;
}
在 main.js
中引入
import { createApp } from 'vue'
import App from './App.vue'
import '@/assets/style/index.scss'
const app = createApp(App)
app.mount('#app')
<style scoped lang="scss">
h1{
color: var(--primary-color)
}
</style>
npm install vue-router@4
// 1.从vue-router导出两个方法使用
import { createRouter, createWebHashHistory } from 'vue-router'
import Layout from '@/layout/index.vue'
// 2.声明菜单数组
const routes = [
{
path: '/',
component: Layout,
redirect: '/home',
title: '首页',
children: [
{
path: 'home',
title: '首页',
component: import('../view/home/index.vue'),
},
{
path: 'about',
title: '关于我',
component: import('../view/about/index.vue'),
},
],
},
]
// 3. 创建路由实例并传递 `routes` 配置
// 你可以在这里输入更多的配置,但我们在这里
// 暂时保持简单
const router = createRouter({
// 4. 内部提供了 history 模式的实现。为了简单起见,我们在这里使用 hash 模式。
history: createWebHashHistory(),
routes, // `routes: routes` 的缩写
})
// 导出路由
export default router
新建 src/layout/index.vue
文件
<template>
<div>
<div
class="d-flex flex-justify-center gap-10 bg-yellow-light flex-items-center navtop"
style="height: 50px"
>
<div
:class="{
active: route.path === '/home' || route.path === '/',
}"
@click="goPage1"
>
首页
</div>
<div
:class="{
active: route.path === '/about',
}"
@click="goPage2"
>
我的
</div>
</div>
<router-view v-slot="{ Component }">
<transition name="fade" mode="out-in">
<component :is="Component" />
</transition>
</router-view>
</div>
</template>
<script setup>
import { useRoute, useRouter } from 'vue-router'
import { ref, watchEffect } from 'vue'
const route = ref(useRoute())
const router = ref(useRouter())
const goPage1 = () => {
router.value.push({
path: '/home',
})
}
const goPage2 = () => {
router.value.push({
path: '/about',
})
}
// 监听路由
watchEffect(() => {
console.log(route.value.path, '5555')
})
</script>
<style scoped lang="scss">
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.2s;
}
.fade-enter,
.fade-leave-to {
opacity: 0;
}
.navtop {
div {
display: flex;
align-items: center;
background-color: #1ab394;
color: white;
height: 100%;
line-height: 100%;
padding: 0 20px;
}
}
.active {
background-color: #1c82e3 !important;
}
</style>
在 main.js
中引入
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
import router from '@/router/index.js'
app.use(router)
app.mount('#app')
import { useRoute, useRouter } from 'vue-router'
const router = ref(useRouter())
const route = ref(useRoute())
// 获取路由信息
const getRouteInfo = () => {
console.log(route.value.path)
console.log(route.value.query)
console.log(route.value.meta)
}
// 路由跳转并传参
const goAbout = () => {
router.value.push({
path: '/about',
query: {
id: '1',
},
})
}
npm install element-plus @element-plus/icons-vue
import { createApp } from 'vue'
import App from './App.vue'
import '@/assets/style/index.scss'
const app = createApp(App)
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import lang from 'element-plus/lib/locale/lang/zh-cn'
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component)
}
app.use(ElementPlus, {
locale: lang,
})
app.mount('#app')
<el-button type="primary" @click="showMsg">成功消息</el-button>
import {ElMessage} from "element-plus";
const showMsg = () => {
ElMessage.success("success")
}
npm install axios
新建 src/utils/request.js
:
import axios from 'axios'
import { ElMessage } from 'element-plus'
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
})
// request拦截器
service.interceptors.request.use(
(config) => {
return config
},
(error) => {
return Promise.reject(error)
}
)
// 响应拦截器
service.interceptors.response.use(
(res) => {
// 未设置状态码则默认成功状态
const code = res.data.code || 200
// 获取错误信息
const msg = res.data.msg
if (code !== 200 && code !== 20000 && code !== 1) {
ElMessage.error(msg)
return Promise.reject('error')
} else {
return res.data
}
},
(error) => {
console.log('err' + error)
let { message } = error
if (message === 'Network Error') {
message = '后端接口连接异常'
} else if (message.includes('Request failed with status code')) {
message = '系统接口' + message.substr(message.length - 3) + '异常'
}
ElMessage({
message: message,
type: 'error',
duration: 5 * 1000,
})
return Promise.reject(error)
}
)
export default service
设置代理,修改 vue.config.js
const port = process.env.port || 10078 // 端口
module.exports = {
devServer: {
host: '0.0.0.0',
port: port,
open: true,
proxy: {
[process.env.VUE_APP_BASE_API]: {
target: `http://xxx.xxx.xxx`,
changeOrigin: true,
pathRewrite: {
['^' + process.env.VUE_APP_BASE_API]: '',
},
},
},
disableHostCheck: true,
},
}
import request from '@/utils/request'
export function testRequestFun() {
return request({
url: `/homePage/getProcessNode`,
method: 'get',
})
}
修改 vue.config.js
const path = require('path')
module.exports = {
configureWebpack: {
resolve: {
alias: {
'@': path.resolve(__dirname, 'src/'),
},
},
},
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。