詳解vite+ts快速搭建vue3項(xiàng)目以及介紹相關(guān)特性
vite
尤大在 Vue 3.0 beta 直播中推薦了 vite 的工具,強(qiáng)調(diào):針對Vue單頁面組件的無打包開發(fā)服務(wù)器,可以直接在瀏覽器運(yùn)行請求的 vue 文件
很新穎,這篇博客用它來搭建一個 vue3 的項(xiàng)目試試
Vite 是面向現(xiàn)代瀏覽器,基于原生模塊系統(tǒng) ESModule 實(shí)現(xiàn)了按需編譯的 Web 開發(fā)構(gòu)建工具。在生產(chǎn)環(huán)境下基于 Rollup 打包
- 快速冷啟動服務(wù)器
- 即時熱模塊更換(HMR)
- 真正的按需編譯
node >= 10.16.0
搭建
使用 vite 搭建項(xiàng)目
npm init vite-app <project-name>
安裝 typescript、vue-router@next、axios、eslint-plugin-vue、sass 等相關(guān)插件
配置
vite.config.ts
vite.config.ts 相當(dāng)于 @vue-cli 項(xiàng)目中的 vue.config.js
我這簡單配置一下:
import path from 'path'
module.exports = {
alias: {
'/@/': path.resolve(__dirname, './src')
},
optimizeDeps: {
include: ['lodash']
},
proxy: {}
}
Router
在 src 下新建 router 文件夾,并在文件夾內(nèi)創(chuàng)建 index.ts
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{
path: '/',
name: 'Home',
component: () => import('/@/views/Home.vue')
},
{
path: '/lifeCycle',
name: 'lifeCycle',
component: () => import('/@/views/LifeCycle.vue')
}
]
export default createRouter({
history: createWebHistory('/krry/'),
routes
})
ts types
項(xiàng)目根目錄下新建 tsconfig.json 寫入相關(guān)配置
{
"compilerOptions": {
...// 其他配置
"paths": {
"/@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"src/types/images.d.ts",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}
src 目錄下新建 types 文件夾,里面需要配置 ts 的類型
shims-vue.d.ts
declare module '*.vue' {}
images.d.ts
declare module '*.svg' declare module '*.png' declare module '*.jpg' declare module '*.jpeg' declare module '*.gif' declare module '*.bmp' declare module '*.tiff'
main.ts
import { createApp } from 'vue'
import router from '/@/router'
import App from '/@/App.vue'
const app = createApp(App)
app.use(router)
app.mount('#app')
然后就可以快樂地寫代碼了
vue3 知識
setup
vue3 中用 setup 函數(shù)整合了所有的 api;只執(zhí)行一次,在生命周期函數(shù)前執(zhí)行,所以在 setup 函數(shù)中拿不到當(dāng)前實(shí)例 this,不能用 this 來調(diào)用 vue2 寫法中定義的方法
它將接受兩個參數(shù):props、context
// props - 組件接受到的屬性 context - 上下文
setup(props, context) {
return {
// 要綁定的數(shù)據(jù)和方法
}
}
props
setup 函數(shù)中的 props 是響應(yīng)式的,當(dāng)傳入新的 prop 時,它將被更新
但是,因?yàn)?props 是響應(yīng)式的,不能使用 ES6 解構(gòu),因?yàn)樗鼤?prop 的響應(yīng)性
如果需要解構(gòu) prop,可以通過使用 setup 函數(shù)中的 toRefs 來安全地完成此操作
import { toRefs } from 'vue'
setup(props) {
const { title } = toRefs(props)
console.log(title.value)
}
context
context 暴露三個組件的 property:{ attrs, slots, emit }
它是一個普通的 JavaScript 對象,不是響應(yīng)式的,這意味著你可以安全地對 context 使用 ES6 解構(gòu)
生命周期
通過在生命周期鉤子前面加上 “on” 來訪問組件的生命周期鉤子
因?yàn)?setup 是圍繞 beforeCreate 和 created 生命周期鉤子運(yùn)行的,所以不需要顯式地定義它們
換句話說,在這兩個鉤子中編寫的任何代碼都應(yīng)該直接在 setup 函數(shù)中編寫
setup() {
onMounted(() => {
console.log('組件掛載')
})
onUnmounted(() => {
console.log('組件卸載')
})
onUpdated(() => {
console.log('組件更新')
})
onBeforeUpdate(() => {
console.log('組件將要更新')
})
onActivated(() => {
console.log('keepAlive 組件 激活')
})
onDeactivated(() => {
console.log('keepAlive 組件 非激活')
})
return {}
}
ref、reactive
ref 可以將某個普通值包裝成響應(yīng)式數(shù)據(jù),僅限于簡單值,內(nèi)部是將值包裝成對象,再通過 defineProperty 來處理的
通過 ref 包裝的值,取值和設(shè)置值的時候,需用通過 .value來進(jìn)行設(shè)置
可以用 ref 來獲取組件的引用,替代 this.$refs 的寫法
reactive 對復(fù)雜數(shù)據(jù)進(jìn)行響應(yīng)式處理,它的返回值是一個 proxy 對象,在 setup 函數(shù)中返回時,可以用 toRefs 對 proxy 對象進(jìn)行結(jié)構(gòu),方便在 template 中使用
使用如下:
<template>
<div>
<div>
<ul v-for="ele in eleList" :key="ele.id">
<li>{{ ele.name }}</li>
</ul>
<button @click="addEle">添加</button>
</div>
<div>
<ul v-for="ele in todoList" :key="ele.id">
<li>{{ ele.name }}</li>
</ul>
<button @click="addTodo">添加</button>
</div>
</div>
</template>
<script>
import { ref, reactive, toRefs } from 'vue'
export default {
setup() {
// ref
const eleList = ref([])
function addEle() {
let len = eleList.value.length
eleList.value.push({
id: len,
name: 'ref 自增' + len
})
}
// reactive
const dataObj = reactive({
todoList: []
})
function addTodo() {
let len = dataObj.todoList.length
dataObj.todoList.push({
id: len,
name: 'reactive 自增' + len
})
}
return {
eleList,
addEle,
addTodo,
...toRefs(dataObj)
}
}
}
</script>
computed、watch
// computed
let sum = computed(() => dataObj.todoList.length + eleList.value.length)
console.log('setup引用computed要.value:' + sum.value)
// watch
watch(
eleList,
(curVal, oldVal) => {
console.log('監(jiān)聽器:', curVal, oldVal)
},
{
deep: true
}
)
watchEffect
響應(yīng)式地跟蹤函數(shù)中引用的響應(yīng)式數(shù)據(jù),當(dāng)響應(yīng)式數(shù)據(jù)改變時,會重新執(zhí)行函數(shù)
const count = ref(0) // 當(dāng) count 的值被修改時,會執(zhí)行回調(diào) const stop = watchEffect(() => console.log(count.value)) // 停止監(jiān)聽 stop()
還可以停止監(jiān)聽,watchEffect 返回一個函數(shù),執(zhí)行后可以停止監(jiān)聽
與 vue2 一樣:
const unwatch = this.$watch('say', curVal => {})
// 停止監(jiān)聽
unwatch()
useRoute、useRouter
import {useRoute, useRouter} from 'vue-router'
const route = useRoute() // 相當(dāng)于 vue2 中的 this.$route
const router = useRouter() // 相當(dāng)于 vue2 中的 this.$router
route 用于獲取當(dāng)前路由數(shù)據(jù)
router 用于路由跳轉(zhuǎn)
vuex
使用 useStore 來獲取 store 對象 從 vuex 中取值時,要注意必須使用 computed 進(jìn)行包裝,這樣 vuex 中狀態(tài)修改后才能在頁面中響應(yīng)
import {useStore} from 'vuex'
setup(){
const store = useStore() // 相當(dāng)于 vue2 中的 this.$store
store.dispatch() // 通過 store 對象來 dispatch 派發(fā)異步任務(wù)
store.commit() // commit 修改 store 數(shù)據(jù)
let category = computed(() => store.state.home.currentCagegory
return { category }
}
到此這篇關(guān)于vite+ts快速搭建vue3項(xiàng)目以及介紹相關(guān)特性的文章就介紹到這了,更多相關(guān)vite+ts搭建vue3內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用jenkins一鍵打包發(fā)布vue項(xiàng)目的實(shí)現(xiàn)
這篇文章主要介紹了使用jenkins一鍵打包發(fā)布vue項(xiàng)目的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05
vue webpack開發(fā)訪問后臺接口全局配置的方法
今天小編就為大家分享一篇vue webpack開發(fā)訪問后臺接口全局配置的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09
vue 實(shí)現(xiàn) rem 布局或vw 布局的方法
這篇文章主要介紹了vue 實(shí)現(xiàn) rem 布局的 或者 vw 布局的方法,本文給提供多種方法,需要的朋友可以參考下2019-11-11
vue style屬性設(shè)置背景圖片的相對路徑無效的解決
這篇文章主要介紹了vue style屬性設(shè)置背景圖片的相對路徑無效的解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10

