In the next generation of front-end development and build tools: Vite article, you created a Vue3 project based on Vite and now start refining the content.
Adding a Path Alias
Previous development used to use @ or _c symbols to abbreviate the path. Configure the alias in vite. Config. js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
The '@': path.resolve(__dirname, './src'),}}})Copy the code
Because paths require absolute paths, you need to use nodeβs path module
vue-router
Install Vue-Router4. x. Note that Vue3 is not supported in Version 3
$ yarn add vue-router@next --save
Copy the code
Add the Router folder and create index.js and routes.js files
import * as VueRouter from 'vue-router';
import routes from './routes';
const router = VueRouter.createRouter({
history: VueRouter.createWebHashHistory(),
routes,
})
export default router;
Copy the code
Routes. Js file
/** * Route configuration file */
export default[{path: '/'.component: () = > import('@/views/dashboard/Home.vue')}]Copy the code
Create the views directory and create the Dashboard directory and the home.vue file
<template>
<div>Home page</div>
</template>
<script>
export default {
name: 'Home'.data() {
return{}}}</script>
Copy the code
Modify main.js to import routes
import { createApp } from 'vue'
import router from './router';
import App from './App.vue'
// Create an instance
const app = createApp(App)
// Mount the route
app.use(router)
// Render instance
app.mount('#app')
Copy the code
Start the project and verify success
$ yarn devYarn Run V1.22.17 Warning Package. json: No license field$ viteVite v2.6.14 Dev Server running at:
> Local: http://localhost:3000/
> Network: use `--host` to expose
ready in 438ms.
Copy the code
Look at the speed. 438ms
vuex
Install version 4.x. Note that version 3.x does not support VUe3
$ yarn add vuex@next --save
Copy the code
Create the store directory and add the index.js file
import { createStore } from 'vuex'
const store = createStore({
state () {
return {
count: 0}},mutations: {
increment (state) {
state.count++
}
}
})
export default store
Copy the code
Modify the main.js file
import store from './store';
/ / mount store
app.use(store)
Copy the code
Modify home.vue to check whether it takes effect
<template>
<div>{{ count }}</div>
</template>
<script>
export default {
name: 'Home'.data() {
return{}},computed: {
count () {
return this.$store.state.count
}
}
}
</script>
Copy the code
If 0 is displayed on the page, store is imported.
conclusion
For time reasons, only the appropriate libraries will be introduced correctly this time.
Vue uses optionsAPI, and we will study composite API later
Note that vue-Router and vuex are imported. The 4. X version is not exported by default.
Vite project is super fast to start, and based on ESM, it is also very convenient for problem location.