一文讓你30分鐘快速掌握Vue3

作者:撒點料兒
經(jīng)過了漫長的迭代,Vue 3.0 終于在上 2020-09-18 發(fā)布了,帶了翻天覆地的變化,使用了 Typescript 進行了大規(guī)模的重構(gòu),帶來了 Composition API RFC 版本,類似 React Hook 一樣的寫 Vue,可以自定義自己的 hook ,讓使用者更加的靈活,接下來總結(jié)一下 vue 3.0 帶來的部分新特性。
setup() ref() reactive() isRef() toRefs() computed() watch() LifeCycle Hooks(新的生命周期) Template refs globalProperties Suspense
Vue2 與 Vue3 的對比
對 TypeScript 支持不友好(所有屬性都放在了 this 對象上,難以推倒組件的數(shù)據(jù)類型) 大量的 API 掛載在 Vue 對象的原型上,難以實現(xiàn) TreeShaking。 架構(gòu)層面對跨平臺 dom 渲染開發(fā)支持不友好 CompositionAPI。受 ReactHook 啟發(fā) 更方便的支持了 jsx Vue 3 的 Template 支持多個根標簽,Vue 2 不支持 對虛擬 DOM 進行了重寫、對模板的編譯進行了優(yōu)化操作...
一、setup 函數(shù)
setup() 函數(shù)是 vue3 中,專門為組件提供的新屬性。它為我們使用 vue3 的 Composition API 新特性提供了統(tǒng)一的入口, setup 函數(shù)會在 beforeCreate 之后、created 之前執(zhí)行, vue3 也是取消了這兩個鉤子,統(tǒng)一用 setup 代替, 該函數(shù)相當于一個生命周期函數(shù),vue 中過去的 data,methods,watch 等全部都用對應的新增 api 寫在 setup()函數(shù)中
setup(props,?context)?{
????context.attrs
????context.slots
????context.parent
????context.root
????context.emit
????context.refs
????return?{
????}
??}
props: 用來接收 props 數(shù)據(jù) context 用來定義上下文, 上下文對象中包含了一些有用的屬性,這些屬性在 vue 2.x 中需要通過 this 才能訪問到, 在 setup() 函數(shù)中無法訪問到 this,是個 undefined 返回值: return {}, 返回響應式數(shù)據(jù), 模版中需要使用的函數(shù)
二、reactive 函數(shù)
reactive() 函數(shù)接收一個普通對象,返回一個響應式的數(shù)據(jù)對象, 想要使用創(chuàng)建的響應式數(shù)據(jù)也很簡單,創(chuàng)建出來之后,在 setup 中 return 出去,直接在 template 中調(diào)用即可
??{{name}}?//?test
<script?lang="ts">
import?{?defineComponent,?reactive,?ref,?toRefs?}?from?'vue';
export?default?defineComponent({
??setup(props,?context)?{
????let?state?=?reactive({
??????name:?'test'
????});
????return?state
??}
});
script>
三、ref() 函數(shù)
ref() 函數(shù)用來根據(jù)給定的值創(chuàng)建一個響應式的數(shù)據(jù)對象,ref() 函數(shù)調(diào)用的返回值是一個對象,這個對象上只包含一個 value 屬性, 只在 setup 函數(shù)內(nèi)部訪問 ref 函數(shù)需要加.value
????<div?class="mine">
????????{{count}}?//?10
????div>
</template>
十二、vue 3.x 完整組件模版結(jié)構(gòu)
一個完成的 vue 3.x 完整組件模版結(jié)構(gòu)包含了:組件名稱、 props、components、setup(hooks、computed、watch、methods 等)
??<div?class="mine"?ref="elmRefs">
????<span>{{name}}span>
????<br>
????<span>{{count}}span>
????<div>
??????<button?@click="handleClick">測試按鈕button>
????div>
????<ul>
??????<li?v-for="item?in?list"?:key="item.id">{{item.name}}li>
????ul>
??div>
template>
vue 3 的生態(tài)
官網(wǎng) 源碼 vite 構(gòu)建器 腳手架:https://cli.vuejs.org/ vue-router-next vuex4.0
UI 組件庫
vant2.x
Ant Design of Vue 2.x
element-plus
專注分享當下最實用的前端技術(shù)。關(guān)注前端達人,與達人一起學習進步!
長按關(guān)注"前端達人"

