> yarn create vite my-vue-app --template vue
> yarn install
- 项目名
- node_modules
- public
- src
- .gitignore
- index.html
- package.json
- vite.config.js
- yarn.lock
> yarn dev
将「main.js」修改成为 「main.ts」
创建ts配置文件「tsconfig.json」,并且添加以下的内容
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
// 这样就可以对 `this` 上的数据属性进行更严格的推断
"strict": true,
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"jsx": "preserve",
"moduleResolution": "node",
"baseUrl": ".",
"paths": {
"@/*":["src/*"]
}
},
"include":[
"src/**/*.ts"
,"src/**/*.d.ts"
,"src/**/*.vue"
]
}
在『src』目录下创建「shims_vue.d.ts」文件,进行类型推导
例如
// shims_vue.d.ts
declare module '*.css' {
const classes : {
[key:string]:string
}
export default classes
}
declare module '*.vue' {
import {defineComponent,FunctionalComponent} from 'vue'
const component:ReturnType<typeof defineComponent>
}
// vite.config.js
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import {resolve} from "path";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve:{
alias:{
'@': resolve(__dirname,'./src')
}
}
})
通过简单例子感受一下vue3的变化。
<template>
<div>默认值:{{a.count}}</div>
<div>{{a.sum}}</div>
<button @click="add()">按钮</button>
<div>{{b}}</div>
</template>
<script lang="ts" setup>
import {reactive,computed,ref} from 'vue'
type Result = {
count:number,
sum:number
}
const a:Result = reactive({
count:100,
sum: computed(() => a.count * 2)
})
const b = ref(10)
function add(){
a.count++;
b.value++
}
</script>
<template>
<input type="text" v-model="a">
<span>{{a}}</span>
</template>
<script lang="ts" setup>
import {reactive,computed,ref} from 'vue'
const a = ref("INet")
</script>
你可以通过在生命周期钩子前面加上 “on” 来访问组件的生命周期钩子。
下表包含如何在 setup () 内部调用生命周期钩子:
选项式 API | Hook inside setup |
---|---|
beforeCreate |
Not needed* |
created |
Not needed* |
beforeMount |
onBeforeMount |
mounted |
onMounted |
beforeUpdate |
onBeforeUpdate |
updated |
onUpdated |
beforeUnmount |
onBeforeUnmount |
unmounted |
onUnmounted |
errorCaptured |
onErrorCaptured |
renderTracked |
onRenderTracked |
renderTriggered |
onRenderTriggered |
activated |
onActivated |
deactivated |
onDeactivated |
- 在『src』目录下创建「hooks」文件夹
- 在『hooks』目录下创建「index.ts」和「userApi.ts」文件
export {userApi}
export default userApi
import {Ref, ref} from "vue"
function userApi<T>(url: RequestInfo , options?:RequestInit){
const response:Ref<T> = ref()
const request = async () => {
const res = await fetch(url,options)
const data = await res.json()
response.value = data
}
return{
response,
request
}
}
export type ApiRequest = () => Promise<void>
export interface UsableApi<T>{
response:Ref<T | undefined>
request:ApiRequest
}
这边使用「Naive UI」举例
> yarn add naive-ui
> yarn add vfonts
import { createApp } from 'vue'
import {
// create naive ui
create,
// component
NButton
} from 'naive-ui'
const naive = create({
components: [NButton]
})
import App from './App.vue'
createApp(App).use(naive).mount('#app')