Vite 构建vue3
使用vite生成vue项目
# npm
npm create vite@latest my-vue-app --template vue
# npm 7+, extra double-dash is needed:
npm create vite@latest my-vue-app -- --template vue
# yarn
yarn create vite my-vue-app --template vue
# pnpm
pnpm create vite my-vue-app --template vue
构建成功后 src目录
安装Router(路由)
npm install vue-router@4
安装后,不会在src下生成route文件夹,所以需要自己创建router文件夹和index.js文件
创建router>index.js 创建文件夹view 和 Home.vue , About.vue文件
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
const routes = [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
main.js 挂载
import router from './router';
const app = createApp(App)
app.use(router).mount('#app')
App.vue
<template>
<router-view></router-view>
</template>
使用
// this.$router => useRouter()
let router = useRouter()
router.push('/about')
// this.$route => useRoute()
安装axios
npm install axios
utils/https.js
import axios from 'axios';
let baseURL = '地址'
const http = axios.create({
baseURL: baseURL,
timeout: 100000
})
// 请求拦截
http.interceptors.request.use(config=>{
return config
},error=>{
console.log(error);
})
// 响应拦截
http.interceptors.response.use((res)=>{
return res.data
})
export default http
main.js引入
import http from './utils/https';
const app = createApp(App)
app.provide('$http', http) // 注入全局
使用
const $http = inject('$http')
$http.get('')
安装Pinia 状态管理库
npm install pinia
在main.js中引入
import { createPinia } from 'pinia'
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
创建store/index.js
import {defineStore} from 'pinia';
export const useStore = defineStore('storeId',{
state:()=>{
return {
names : 'ying',
age : 18
}
},
getters:{
changeMoney(){
return this.money + 500
}
},
actions:{
addMoney(value){
this.money += value
}
}
})
pinia简单使用
<template>
<button @click="changes">修改</button>
<div>姓名:{{ names }}</div>
<div>年龄:{{ age }}</div>
<div>money:{{ changeMoney }}</div>
<button @click="btn">actions</button>
<button @click="reset">重置</button>
</template>
<script setup>
import { useStore } from '@/store/index';
import {storeToRefs} from 'pinia';
const store = useStore();
let {names, age, changeMoney} = storeToRefs(store)
const changeAge = ()=>{
// 第一种修改方法
// age.value +=1
// 第二种修改方法 可以不用 let { names ...} = storeToRefs(store)
// 直接 {{ state.age }}
store.$patch(state=>{
state.age+=1
state.money += 500
})
}
// 触发actions
const btn = ()=>{
store.addMoney(500)
}
// 重置
const reset = ()=>{
store.$reset()
}
</script>