This article is reproduced from the WeChat public account: Some of the front-end play, the author's front-end attacker
This article will take you from zero to build a basis
Vue3.0
ofvite
theVue3.0
development environment, by learning this article, you will learn the following:
-
Use the
vite
initialVue3.0
project -
Configuration
ts
-
Configuration
vue-router
-
Configuration
vuex
-
Use to
Vue3.0
develop anTodoList
example
One, use the vite
initialization project
vite introduction
vite
It is a new tool created by Youda this year, and vite
the description of it is this: Vite is an opinionated web dev build tool that serves your code via native ES Module imports during dev and bundles it with Rollup for production. Translated into Chinese means: Vite
is a development and construction tool ES Module
driven by native Web
. It is based on the browser's native ES imports
development in the development environment, and based on the Rollup
packaging in the production environment .
Why use vite
Why is it especially launched? vite
When we use webpack
it, it takes tens of seconds or even more than a minute to start a project every time it develops, which is relatively slow, and hot updates are relatively slow, and vite
the main feature is fast. The official website vite
is characterized by Described like this
-
Fast cold start
-
Instant module hot update
-
True on-demand compilation
How fast is it? Let’s try a new project first
Initialize the vite project
-
Initialize the project, open a terminal window in the workspace, for the
window
user,cmd
and then execute the following commandyarn create vite-app my-vue3
After the execution, the following content will be output, you can see that the new project is very fast, just use
1.63s
-
After initializing the project,
cd my-vue3
go to the project and then execute theyarn
installation dependency (it is recommended to use Taobao mirror here, which is faster) -
Dependent installation needs to
yarn dev
start the projectDid you experience the feeling of the Miaoqi project in an instant? After starting, you can
http://localhost:3000
access the project
View project structure
After using the vscode
open project, you can see that the newly vue-cli4
created project structure is basically the same as the created project structure, which are both familiar App.vue
andmain.js
View the contents of the main.js file
turn onmain.js
import { createApp } from'vue'
import App from'./App.vue'
import'./index.css'
createApp(App).mount('#app')
Found that Vue
the method of creation has changed. The original new Vue
method is used to initialize Vue
. In Vue3.0
, the method of modification is changed to pass createApp
. For Vue3.0
more usage methods, we will gradually explain to you in the following series of articles.
Two, configure typescript
typescript
It has now become one of the necessary front-end skills, and a large number of projects have begun to typescript
be developed based on them. When using Vue2.0
it, because Vue2.0
there is no typescript
support for it, it is a ts
bit awkward to use the development function. But when it comes Vue3
, its own source code is based on ts
development, so it ts
has good support for innate. The vite
configuration typescript
is very simple, only the following steps are required.
-
installation
typescript
yarn add typescript -D
-
initialization
tsconfig.json
# 然后在控制台执行下面命令 npx tsc --init
-
Will be
main.js
modified tomain.ts
, andindex.html
the reference inside will also be modified tomain.ts
, through the need to modifyApp.vue
andHelloWorld.vue
file, the modification method is as follows<!--将 <script> 修改为 <script lang="ts">--> <script lang="ts"> import HelloWorld from './components/HelloWorld.vue' export default { name: 'App', components: { HelloWorld } } </script>
After the modification, restart to access the project. Although this configuration is possible, you
main.ts
will find animport App from App.vue
error when you open it :,Cannot find module './App.vue' or its corresponding type declarations.
This is because the filets
has not been recognized yetvue
, and the following configuration is required:Then you can happily use
ts
it in the component-
Add
shim.d.ts
files to the project root directory -
Add the following
declare module"*.vue" { import { Component } from"vue"; const component: Component; exportdefault component; }
-
Three, configuration vue-router
In Vue2.0
the route we will generally choose to use vue-router
, in Vue3.0
use remain vue-router
, however, and Vue3.0
as the current vue-router
version is the beta
version at the time of this writing, the version is4.0.0-beta7
installationvue-router
Because the current vue-router
for the vue3.0
version or beta
versions can not be directly yarn add vue-router
installed, but need to bring the version number
yarn add [email protected]
Configure vue-router
src
Create a new router
directory under the project directory , then add a index.ts
file, add the following content to the file
import {createRouter, createWebHashHistory} from'vue-router'
// 在 Vue-router新版本中,需要使用createRouter来创建路由
exportdefault createRouter({
// 指定路由的模式,此处使用的是hash模式
history: createWebHashHistory(),
// 路由地址
routes: []
})
Vue3.0
Just as the new initialization method has changed, vue-router
the initialization method has also changed, becoming a pass createRouter
to initialize routing.
It will be router
introduced into main.ts
the
Modify the main.ts
contents of the file as follows
import { createApp } from'vue'
import App from'./App.vue'
import'./index.css'
import router from'./router/index'
const app = createApp(App)
// 通过use 将 路由插件安装到 app 中
app.use(router)
app.mount('#app')
Four, configure vuex
Same vue-router
as the new vuex
current beta
version, the current version is4.0.0-beta.4
Install vuex
yarn add [email protected]
Configure vuex
src
Create a new store
directory under the project directory , and add a index.ts
file, add the following content to the file
import { createStore } from'vuex'
interface State {
userName: string
}
exportdefault createStore({
state(): State {
return {
userName: "子君",
};
},
});
Introduced into main.ts
the
import { createApp } from'vue'
import App from'./App.vue'
import'./index.css'
import router from'./router/index'
import store from'./store/index'
const app = createApp(App)
app.use(router)
app.use(store)
app.mount('#app')
Develop TodoList
Through the above series of operations, our development environment has been configured, and then we will first develop one through the new development environment TodoList
to verify whether it is normal.
Add todolist
page
-
First, we first
src
create a new directory under theviews
directory, then create a new file in ittodo-list.vue
, and add the following content to the file<template> <div class="todo-list"> <div> <label>新增待办</label> <input v-model="state.todo" @keyup.enter="handleAddTodo"> </div> <div> <h3>待办列表({ {todos.length}})</h3> <ul> <li v-for="item in todos" :key="item.id" @click="handleChangeStatus(item, true)"> <input type="checkbox"> <label>{ {item.text}}</label> </li> </ul> </div> <div><h3>已办列表({ {dones.length}})</h3></div> <ul> <li v-for="item in dones" :key="item.id" @click="handleChangeStatus(item, false)"> <input type="checkbox" checked> <label>{ {item.text}}</label> </li> </ul> </div> </template> <script lang="ts"> // 在vue2中 data 在vue3中使用 reactive代替 import { reactive, computed } from 'vue' import { useRouter } from 'vue-router' export default { // setup相当于vue2.0的 beforeCreate和 created,是vue3新增的一个属性,所有的操作都在此属性中完成 setup(props, context) { // 通过reactive 可以初始化一个可响应的数据,与Vue2.0中的Vue.observer很相似 const state = reactive({ todoList: [{ id: 1, done: false, text: '吃饭' },{ id: 2, done: false, text: '睡觉' },{ id: 3, done: false, text: '打豆豆' }], todo: '' }) // 使用计算属性生成待办列表 const todos = computed(() => { return state.todoList.filter(item => !item.done) }) // 使用计算属性生成已办列表 const dones = computed(() => { return state.todoList.filter(item => item.done) }) // 修改待办状态 const handleChangeStatus = (item ,status) => { item.done = status } // 新增待办 const handleAddTodo = () => { if(!state.todo) { alert('请输入待办事项') return } state.todoList.push({ text: state.todo, id: Date.now(), done: false }) state.todo = '' } // 在Vue3.0中,所有的数据和方法都通过在setup 中 return 出去,然后在template中使用 return { state, todos, dones, handleChangeStatus, handleAddTodo } } } </script> <style scoped> .todo-list{ text-align: center; } .todo-list ul li { list-style: none; } </style>
Adjust routing
-
First
App.vue
modify the content of the file to<template> <router-view></router-view> </template> <script lang="ts"> export default { name: 'App' } </script>
-
Then modify the
router/index.ts
file and add a new routeimport {createRouter, createWebHashHistory} from'vue-router' // 在 Vue-router新版本中,需要使用createRouter来创建路由 exportdefault createRouter({ // 指定路由的模式,此处使用的是hash模式 history: createWebHashHistory(), // 路由地址 routes: [{ path: '/todolist', // 必须添加.vue后缀 component: () =>import('../views/todo-list.vue') }] })
At this time, we can
http://localhost:3000/#/todolist
visitTodoList
through, the effect is shown in the figure below
-
to sum up
At this point, our Vue3.0
development environment is considered complete. Of course, there are still many things to be improved. For example, we need to adjust typescript
the configuration and add it eslint
.