## 一、创建Vite项目 选择Vue模板 ```bash npm create vite@latest [projectNmae] -- --template vue ``` ## 二、引入/使用模块 #### 1、路由模块 安装 ```bash npm install vue-router@4 ``` 在 `/src` 目录下创建 `router/index.js` 文件 ```js import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router' import HomeView from '../views/HomeView.vue' const routes = [ { path: '/', name: 'home', component: HomeView }, { path: '/about', name: 'about', component: () => import('../views/AboutView.vue') // 动态导入 } ] const router = createRouter({ history: createWebHashHistory(), // createWebHistory(import.meta.env.BASE_URL), routes }) export default router ``` 在 `main.js` 中导入并使用 ```js import { createApp } from 'vue' import App from './App.vue' import router from './router' // 导入路由配置 const app = createApp(App) app.use(router) // 使用路由 app.mount('#app') ``` 标签式路由 ```html Home About ``` 编译式路由 ```html Home About ``` 引用传入参数 ```html ``` 全局守卫 ```js // 在 router/index.js router.beforeEach((to, from, next) => { // 从 store 获取认证状态 if (to.meta.requiresAuth && !store.state.user.isAuthenticated) { next('/login') } else { next() } }) ``` #### 2、状态管理模块 ##### `vuex` 安装 ```bash npm install vuex@next ``` 在 `/src` 目录下创建 `store/index.js` 文件 ```js import {createStore} from 'vuex' export default createStore({ state: { // 全局属性 num: 10 }, getters: { // 全局计算属性 changeNum(state) { return state.num * state.num; } }, mutations: { // 改变全局属性的同步方法 addNum(state, param) { state.num += param; } }, actions: { // 改变全局属性的异步方法 addNum(state, param) { setTimeout(() => { state.commit('addNum', param) }, 3000) } }, modules: { // 其他store模板引入 } }) ``` 在 `main.js` 中导入并使用 ```js import { createApp } from 'vue' import App from './App.vue' import router from './router' import store from './store' // 导入 Vuex store const app = createApp(App) app.use(router) app.use(store) // 使用 Vuex app.mount('#app') ``` 在组件中使用 `Store` ```html ``` ##### `pinia` 安装 ```bash npm install pinia ``` 在 `/src` 目录下创建 `stores/counter.js` 文件 ```js import { defineStore } from 'pinia' export const useCounterStore = defineStore('counter', { state: () => ({ // 全局属性 count: 0 }), actions: { // 改变全局属性的同步/异步方法 increment() { this.count++ } }, getters: { // 全局计算属性 doubleCount: (state) => state.count * 2 } }) ``` 在 `main.js` 中导入并使用 ```js import { createApp } from 'vue' import { createPinia } from 'pinia' // 导入 Pinia import App from './App.vue' import router from './router' const app = createApp(App) app.use(router) app.use(createPinia()) // 使用 Pinia app.mount('#app') ``` 在组件中使用 `Store` ```html Count: {{ counter.count }} Double: {{ counter.doubleCount }} Increment Async Increment ``` #### 3、生命周期函数 ```html 组件 ``` #### 4、数据监听 ```html 组件 change ``` #### 5、DOM对象获取 ```html 组件 我是一个DOM对象 ``` #### 6、Axios框架 安装 ```bash npm install axios ``` 使用 ```html ``` #### 7、Cookie设置 安装 ```bash npm install vue-cookies -S ``` 在`main.js`引用 ```js import VueCookies from "vue-cookies"; app.use(VueCookies); ``` 使用 ```js import cookies from "vue-cookies"; // 设置cookie cookies.set('key', 'value', time); // 获取cookie this.$cookies.get('key'); // 删除cookies this.$cookies.remove('key'); // 查看cookie this.$cookies.isKey('key'); // return false or true // 获取所有cookies this.$cookies.keys() // return a array ``` #### 8、跨域请求携带Cookie ```js axios.defaults.withCredentials = true; ``` #### 9、Base64编码 安装 ```bash npm install --save js-base64 ``` 使用 ```js import { Base64 } from 'js-base64'; let password = "123456"; let encodedPwd = Base64.encode(password); // 加密 let decodedPwd = Base64.decode(encodedPwd); // 解密 console.log("加密后的密码:", encodedPwd); // 输出: 加密后的密码: MTIzNDU2 console.log("解密后的密码:", decodedPwd); // 输出: 解密后的密码: 123456 ``` #### 10、过渡与动画 [Vue3过渡与动画](https://www.soki.me/archives/334.html) ## 三、组件通信 #### 1、父组件→子组件 ```html 父组件 子组件 ``` #### 2、子组件→父组件 ```html 给父组件传值 ``` #### 3、孙子组件→祖父组件 ```html 孙子组件 ``` ## 四、配置修改 #### 1、代理服务器 ```js import {defineConfig} from 'vite' import vue from '@vitejs/plugin-vue' // https://vite.dev/config/ export default defineConfig({ plugins: [vue()], server: { historyApiFallback: true, proxy: { '/api': { target: 'http://localhost:3000', changeOrigin: true, secure: false, rewrite: (path) => path.replace(/^\/api/, '') } }, port: 9870 } }) ``` ## 五、常用的组件库 #### 1、Ant Design ##### 安装 ```bash ## 组件库 npm install ant-design-vue@4.x --save ## 图标库 npm install --save @ant-design/icons-vue ``` ##### 注册 如果使用 Vue 默认的模板语法,需要注册组件后方可使用,有如下三种方式注册组件: **全局完整注册** ```jsx import { createApp } from 'vue'; import App from './App'; import Antd from 'ant-design-vue'; import 'ant-design-vue/dist/reset.css'; const app = createApp(App); app.use(Antd).mount('#app'); ``` 以上代码便完成了 Antd 的全局注册。需要注意的是,样式文件需要单独引入。 **全局部分注册** ```jsx import { createApp } from 'vue'; import { Button, message } from 'ant-design-vue'; import App from './App'; const app = createApp(App); /* 会自动注册 Button 下的子组件, 例如 Button.Group */ app.use(Button).mount('#app'); app.config.globalProperties.$message = message; ``` **局部注册组件** 此种方式需要分别注册组件子组件,如 Button、ButtonGroup,并且注册后仅在当前组件中有效。所以我们推荐使用上述两种方式。 ```html Add ``` ##### 详细文档 [快速上手 - Ant Design Vue](https://www.antdv.com/docs/vue/getting-started-cn) [组件总览 - Ant Design Vue](https://www.antdv.com/components/overview-cn/) #### 2、Element Plus ##### 安装 ```bash npm install element-plus --save ``` ##### 注册 **全局完整注册** 如果对打包后的文件大小不是很在乎,那么使用完整导入会更方便。 ```js import { createApp } from 'vue' import ElementPlus from 'element-plus' import 'element-plus/dist/index.css' import App from './App.vue' const app = createApp(App) app.use(ElementPlus) app.mount('#app') ``` **自动按需导入** 首先需要安装`unplugin-vue-components` 和 `unplugin-auto-import`这两款插件 ```bash npm install -D unplugin-vue-components unplugin-auto-import ``` 然后把下列代码插入到 `Vite` 或 `Webpack` 的配置文件中 ```js // vite.config.js import { defineConfig } from 'vite' import AutoImport from 'unplugin-auto-import/vite' import Components from 'unplugin-vue-components/vite' import { ElementPlusResolver } from 'unplugin-vue-components/resolvers' export default defineConfig({ // ... plugins: [ // ... AutoImport({ resolvers: [ElementPlusResolver()], }), Components({ resolvers: [ElementPlusResolver()], }), ], }) ``` ```js // webpack.config.js const AutoImport = require('unplugin-auto-import/webpack') const Components = require('unplugin-vue-components/webpack') const { ElementPlusResolver } = require('unplugin-vue-components/resolvers') module.exports = { // ... plugins: [ AutoImport({ resolvers: [ElementPlusResolver()], }), Components({ resolvers: [ElementPlusResolver()], }), ], } ``` ##### 详细文档 [快速开始 | Element Plus](https://element-plus.org/zh-CN/guide/quickstart) [Overview 组件总览 | Element Plus](https://element-plus.org/zh-CN/component/overview) #### 3、TailwindCSS ##### 安装 通过 npm 安装 `tailwindcss` 和 `@tailwindcss/vite`。 ```bash npm install tailwindcss @tailwindcss/vite ``` ##### 配置 Vite 插件 将 `@tailwindcss/vite` 插件添加到 `Vite` 配置中。 ```js import { defineConfig } from 'vite' import tailwindcss from '@tailwindcss/vite' // 这一行 export default defineConfig({ plugins: [ tailwindcss(), // 这一行 ], }) ``` ##### 导入 Tailwind CSS 在全局 CSS 文件中添加 `@import`,以导入 Tailwind CSS。 ```css @import "tailwindcss"; ``` ##### 详细文档 [使用 Vite 安装 Tailwind CSS - Tailwind CSS 框架](https://tailwind.org.cn/docs/installation/using-vite) Loading... ## 一、创建Vite项目 选择Vue模板 ```bash npm create vite@latest [projectNmae] -- --template vue ``` ## 二、引入/使用模块 #### 1、路由模块 安装 ```bash npm install vue-router@4 ``` 在 `/src` 目录下创建 `router/index.js` 文件 ```js import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router' import HomeView from '../views/HomeView.vue' const routes = [ { path: '/', name: 'home', component: HomeView }, { path: '/about', name: 'about', component: () => import('../views/AboutView.vue') // 动态导入 } ] const router = createRouter({ history: createWebHashHistory(), // createWebHistory(import.meta.env.BASE_URL), routes }) export default router ``` 在 `main.js` 中导入并使用 ```js import { createApp } from 'vue' import App from './App.vue' import router from './router' // 导入路由配置 const app = createApp(App) app.use(router) // 使用路由 app.mount('#app') ``` 标签式路由 ```html <!-- src/App.vue --> <template> <div> <nav> <router-link to="/">Home</router-link> <router-link to="/about" :query="{name: '张三'}">About</router-link> </nav> <router-view /> </div> </template> ``` 编译式路由 ```html <!-- src/App.vue --> <template> <nav> <button @click="toHome">Home</button> <button @click="toAbout">About</button> </nav> <router-view/> </template> <script setup> import {useRouter} from "vue-router"; const router = useRouter(); function toHome() { router.push("/"); } function toAbout() { router.push({ path: "/about", query: { name: "张三" } }); } </script> ``` 引用传入参数 ```html <script setup> import {useRoute} from "vue-router"; const route = useRoute(); console.log(route.query.name); </script> ``` 全局守卫 ```js // 在 router/index.js router.beforeEach((to, from, next) => { // 从 store 获取认证状态 if (to.meta.requiresAuth && !store.state.user.isAuthenticated) { next('/login') } else { next() } }) ``` #### 2、状态管理模块 ##### `vuex` 安装 ```bash npm install vuex@next ``` 在 `/src` 目录下创建 `store/index.js` 文件 ```js import {createStore} from 'vuex' export default createStore({ state: { // 全局属性 num: 10 }, getters: { // 全局计算属性 changeNum(state) { return state.num * state.num; } }, mutations: { // 改变全局属性的同步方法 addNum(state, param) { state.num += param; } }, actions: { // 改变全局属性的异步方法 addNum(state, param) { setTimeout(() => { state.commit('addNum', param) }, 3000) } }, modules: { // 其他store模板引入 } }) ``` 在 `main.js` 中导入并使用 ```js import { createApp } from 'vue' import App from './App.vue' import router from './router' import store from './store' // 导入 Vuex store const app = createApp(App) app.use(router) app.use(store) // 使用 Vuex app.mount('#app') ``` 在组件中使用 `Store` ```html <template> <div> <p v-text="$store.state.num"></p> <p v-text="$store.getters.changeNum"></p> <p v-text="this.$route.query.name"></p> </div> </template> <script setup> // 获取store对象 const store = useStore(); console.log(store.state.num); </script> ``` ##### `pinia` 安装 ```bash npm install pinia ``` 在 `/src` 目录下创建 `stores/counter.js` 文件 ```js import { defineStore } from 'pinia' export const useCounterStore = defineStore('counter', { state: () => ({ // 全局属性 count: 0 }), actions: { // 改变全局属性的同步/异步方法 increment() { this.count++ } }, getters: { // 全局计算属性 doubleCount: (state) => state.count * 2 } }) ``` 在 `main.js` 中导入并使用 ```js import { createApp } from 'vue' import { createPinia } from 'pinia' // 导入 Pinia import App from './App.vue' import router from './router' const app = createApp(App) app.use(router) app.use(createPinia()) // 使用 Pinia app.mount('#app') ``` 在组件中使用 `Store` ```html <template> <div> <p>Count: {{ counter.count }}</p> <p>Double: {{ counter.doubleCount }}</p> <button @click="counter.increment()">Increment</button> <button @click="counter.incrementAsync()">Async Increment</button> </div> </template> <script setup> import {useCounterStore} from "../stores/counter.js"; const counter = useCounterStore(); // 无响应性 // 直接使用 counter.count, counter.doubleCount, counter.increment() // 或者使用解构(需要保持响应性) import { storeToRefs } from 'pinia'; const { count, doubleCount } = storeToRefs(counter); const { increment, incrementAsync } = counter; // 或者使用计算属性(需要保持响应性) // const count = computed(() => counter.count); // const doubleCount = computed(() => counter.doubleCount); // const increment = () => { // counter.increment() // }; </script> ``` #### 3、生命周期函数 ```html <template> <div> <h2>组件</h2> </div> </template> <script setup> import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated } from "vue"; console.log("这是setup函数"); // undefined console.log(this); // 挂载前 onBeforeMount(() => { console.log("组件onBeforeMount"); }); // 挂载后 onMounted(() => { console.log("组件onMounted"); }); // 数据更新前 onBeforeUpdate(() => { console.log("组件onBeforeUpdate"); }); // 数据更新后 onUpdated(() => { console.log("组件onUpdated"); }); // 卸载挂载前 onBeforeUnmount(() => { console.log("组件onBeforeUnmount"); }); // 卸载挂载后 onUnmounted(() => { console.log("组件onUnmounted"); }); </script> <style scoped> </style> ``` #### 4、数据监听 ```html <template> <div> <h2>组件</h2> <span v-text="num"></span> <br> <span v-text="newNum"></span> <br> <span v-text="user"></span> <br> <button @click="change">change</button> </div> </template> <script setup> import { ref, computed, watch } from "vue"; const num = ref(10); const user = ref({ userId: 100, userName: "张三" }); // watch监听普通数据 watch(num, (newValue, oldValue) => { console.log("watch监听1"); console.log(newValue, oldValue); }); // watch监听对象属性 watch(() => { return user.value.userName }, (oldValue, newValue) => { console.log("watch监听2"); console.log(newValue, oldValue); }); function change() { num.value++; // 引用式数据可直接修改其内部值 user.value.userName = "李四"; } </script> <style scoped> </style> ``` #### 5、DOM对象获取 ```html <template> <div> <h2>组件</h2> <div ref="DOMobj">我是一个DOM对象</div> </div> </template> <script setup> import { ref, onMounted } from "vue"; // 声明响应式数据去绑定DOM对象 let DOMobj = ref(null); // 挂载后 onMounted(() => { // 获取DOM对象 console.log(DOMobj); console.log("组件onMounted"); }); </script> <style scoped> </style> ``` #### 6、Axios框架 安装 ```bash npm install axios ``` 使用 ```html <script setup> import axios from "axios"; import {ref} from "vue"; const data = ref({}); // GET请求 axios.get('网址', { params: { key: "value", } }).then((response) => { data.value = response.data; console.log(data); }).catch((error) => { console.log(error) }); </script> ``` #### 7、Cookie设置 安装 ```bash npm install vue-cookies -S ``` 在`main.js`引用 ```js import VueCookies from "vue-cookies"; app.use(VueCookies); ``` 使用 ```js import cookies from "vue-cookies"; // 设置cookie cookies.set('key', 'value', time); // 获取cookie this.$cookies.get('key'); // 删除cookies this.$cookies.remove('key'); // 查看cookie this.$cookies.isKey('key'); // return false or true // 获取所有cookies this.$cookies.keys() // return a array ``` #### 8、跨域请求携带Cookie ```js axios.defaults.withCredentials = true; ``` #### 9、Base64编码 安装 ```bash npm install --save js-base64 ``` 使用 ```js import { Base64 } from 'js-base64'; let password = "123456"; let encodedPwd = Base64.encode(password); // 加密 let decodedPwd = Base64.decode(encodedPwd); // 解密 console.log("加密后的密码:", encodedPwd); // 输出: 加密后的密码: MTIzNDU2 console.log("解密后的密码:", decodedPwd); // 输出: 解密后的密码: 123456 ``` #### 10、过渡与动画 [Vue3过渡与动画](https://www.soki.me/archives/334.html) ## 三、组件通信 #### 1、父组件→子组件 ```html <template> <div> <h2>父组件</h2> <span v-text="num"></span> <br> <span v-text="newNum"></span> <br> <span v-text="user"></span> <h2>子组件</h2> <hello :params="{num,newNum,user}" @childMsg="getChildMsg"></hello> </div> </template> <script setup> import { ref, computed, provide } from "vue"; import Hello from "@/components/Hello.vue"; import {useStore} from "vuex"; const num = ref(10); const user = ref({ userId: 100, userName: "张三" }); let newNum = computed(() => { return num.value * num.value; }); function getChildMsg(msg) { alert(msg); } // 向孙子组件通讯 provide('msg', user); </script> <style scoped> </style> ``` #### 2、子组件→父组件 ```html <template> <div> <span v-text="params.num"></span><br> <span v-text="params.newNum"></span><br> <span v-text="params.user"></span><br> <button @click="sendMsg">给父组件传值</button> <hr> <GrandSon></GrandSon> </div> </template> <script setup> import {onBeforeUnmount, onUnmounted} from "vue"; import GrandSon from "@/components/GrandSon.vue"; const props = defineProps({ params: Object }); //获取emits函数对象 const emits = defineEmits(['childMsg']) console.log(props); //给父组件传值 function sendMsg() { emits("childMsg", "这是给父组件传的值"); } </script> <style scoped> </style> ``` #### 3、孙子组件→祖父组件 ```html <template> <div> <h2>孙子组件</h2> <span v-text="msg"></span><br> </div> </template> <script setup> import {inject} from "vue"; const msg = inject('msg'); console.log(msg); </script> <style scoped> </style> ``` ## 四、配置修改 #### 1、代理服务器 ```js import {defineConfig} from 'vite' import vue from '@vitejs/plugin-vue' // https://vite.dev/config/ export default defineConfig({ plugins: [vue()], server: { historyApiFallback: true, proxy: { '/api': { target: 'http://localhost:3000', changeOrigin: true, secure: false, rewrite: (path) => path.replace(/^\/api/, '') } }, port: 9870 } }) ``` ## 五、常用的组件库 #### 1、Ant Design ##### 安装 ```bash ## 组件库 npm install ant-design-vue@4.x --save ## 图标库 npm install --save @ant-design/icons-vue ``` ##### 注册 如果使用 Vue 默认的模板语法,需要注册组件后方可使用,有如下三种方式注册组件: **全局完整注册** ```jsx import { createApp } from 'vue'; import App from './App'; import Antd from 'ant-design-vue'; import 'ant-design-vue/dist/reset.css'; const app = createApp(App); app.use(Antd).mount('#app'); ``` 以上代码便完成了 Antd 的全局注册。需要注意的是,样式文件需要单独引入。 **全局部分注册** ```jsx import { createApp } from 'vue'; import { Button, message } from 'ant-design-vue'; import App from './App'; const app = createApp(App); /* 会自动注册 Button 下的子组件, 例如 Button.Group */ app.use(Button).mount('#app'); app.config.globalProperties.$message = message; ``` **局部注册组件** 此种方式需要分别注册组件子组件,如 Button、ButtonGroup,并且注册后仅在当前组件中有效。所以我们推荐使用上述两种方式。 ```html <template> <a-button>Add</a-button> </template> <script> import { Button } from 'ant-design-vue'; const ButtonGroup = Button.Group; export default { components: { AButton: Button, AButtonGroup: ButtonGroup, }, }; </script> ``` ##### 详细文档 [快速上手 - Ant Design Vue](https://www.antdv.com/docs/vue/getting-started-cn) [组件总览 - Ant Design Vue](https://www.antdv.com/components/overview-cn/) #### 2、Element Plus ##### 安装 ```bash npm install element-plus --save ``` ##### 注册 **全局完整注册** 如果对打包后的文件大小不是很在乎,那么使用完整导入会更方便。 ```js import { createApp } from 'vue' import ElementPlus from 'element-plus' import 'element-plus/dist/index.css' import App from './App.vue' const app = createApp(App) app.use(ElementPlus) app.mount('#app') ``` **自动按需导入** 首先需要安装`unplugin-vue-components` 和 `unplugin-auto-import`这两款插件 ```bash npm install -D unplugin-vue-components unplugin-auto-import ``` 然后把下列代码插入到 `Vite` 或 `Webpack` 的配置文件中 ```js // vite.config.js import { defineConfig } from 'vite' import AutoImport from 'unplugin-auto-import/vite' import Components from 'unplugin-vue-components/vite' import { ElementPlusResolver } from 'unplugin-vue-components/resolvers' export default defineConfig({ // ... plugins: [ // ... AutoImport({ resolvers: [ElementPlusResolver()], }), Components({ resolvers: [ElementPlusResolver()], }), ], }) ``` ```js // webpack.config.js const AutoImport = require('unplugin-auto-import/webpack') const Components = require('unplugin-vue-components/webpack') const { ElementPlusResolver } = require('unplugin-vue-components/resolvers') module.exports = { // ... plugins: [ AutoImport({ resolvers: [ElementPlusResolver()], }), Components({ resolvers: [ElementPlusResolver()], }), ], } ``` ##### 详细文档 [快速开始 | Element Plus](https://element-plus.org/zh-CN/guide/quickstart) [Overview 组件总览 | Element Plus](https://element-plus.org/zh-CN/component/overview) #### 3、TailwindCSS ##### 安装 通过 npm 安装 `tailwindcss` 和 `@tailwindcss/vite`。 ```bash npm install tailwindcss @tailwindcss/vite ``` ##### 配置 Vite 插件 将 `@tailwindcss/vite` 插件添加到 `Vite` 配置中。 ```js import { defineConfig } from 'vite' import tailwindcss from '@tailwindcss/vite' // 这一行 export default defineConfig({ plugins: [ tailwindcss(), // 这一行 ], }) ``` ##### 导入 Tailwind CSS 在全局 CSS 文件中添加 `@import`,以导入 Tailwind CSS。 ```css @import "tailwindcss"; ``` ##### 详细文档 [使用 Vite 安装 Tailwind CSS - Tailwind CSS 框架](https://tailwind.org.cn/docs/installation/using-vite) 最后修改:2025 年 11 月 10 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 👆请简单粗暴地爱我。