vue進階之路:vue3.2-setup語法糖、組合式API、狀態庫Pinia歸納總結

語言: CN / TW / HK

大家好,我叫東東吖,你現在看到的是vue進階系列,如果覺得不錯,可以點贊收藏哦,喜歡我的朋友,還可以加個關注鴨。

vue進階系列包括以下內容:

vue進階之路:元件通訊的8種方式,你搞清楚了嗎?

vue進階之路:父子元件的生命週期執行流程是怎麼樣的呢?

vue進階之路:vuex五大核心概念,看完這篇文章就夠了。

vue進階之路:前端技術日新月異,vue3.0的時代已經來臨...

vue進階之路:叮,Vue2與Vue3都有哪些區別?請查收!

前言:

vue3.0都沒學完,vue3.2又來了,你還學得動嗎?(手動滑稽)

vue3.2與vue3.0在語法上存在以下區別: \ vue3.0版本:變數和方法必須return出來才能使用。\ vue3.2版本:只需要在script標籤上加上setup屬性,不需要再把變數和方法return出去,程式碼更加簡潔。

本文將重點將重點介紹vue3.2版本的語法,如果對vue3還沒有完全接觸過的小夥伴,可以先移步去我這篇文章熱熱身哦。 前端技術日新月異,vue3.0的時代已經來臨...

建立專案:

vite腳手架建立專案: vue3+vite2+ts npm create vite@latest

一.元件結構

```

```

二.data

```

```

三.method

```

```

四.computed

```

```

五.父傳子

``` //父元件:

```

``` //子元件:

```

六.子傳父

``` //父元件:

```

``` //子元件:

```

七.原型鏈繫結和元件使用

``` //main.ts

// 建立vue例項 const app=createApp(App) // 獲取原型 const prototype = app.config.globalProperties // 繫結引數 prototype.name = '我是掛載在全域性上的屬性' ```

``` //元件內獲取使用

//引入 import { getCurrentInstance } from "vue"; // 獲取原型 const { proxy } = getCurrentInstance(); // 輸出 console.log(proxy.name);

```

八.任意元件通訊mitt.js

  • Vue2.x使用EventBus進行元件通訊,而Vue3.x推薦使用mitt.js。

九.雙向繫結v-model

``` //父元件:

//子元件:

```

十.nextTick

```

子元件:

```

十一.插槽

``` //子元件:

```

``` //父元件:

//頁面展示情況:

我是預設插槽

我是具名插槽1

我是具名插槽2

我是具名插槽3

作用域插槽——姓名:東東吖,年齡25歲 ```

十二.路由useRoute和useRouter

``` //新建router/index.ts

import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'; const routes: Array = [ { path: '/', redirect: '/home' }, { path: '/home', name: 'home', component: () => import('../pages/home/Index.vue'), meta: { showFooter: true, requireAuth: false, } }, { path: '/about', name: 'about', component: () => import( '../pages/about/Index.vue'), meta: { showFooter: true, requireAuth: false, } },

];

const router = createRouter({ history: createWebHashHistory(), routes, });

export default router; ```

``` //在main.ts將路由router註冊 import { createApp } from 'vue' import App from './App.vue' import router from './router/index.ts'

const app=createApp(App) app.use(router).mount('#app')

```

``` //在頁面列印結果

import { useRouter, useRoute } from "vue-router";

// 必須先宣告呼叫 const router = useRouter(); const route = useRoute();

// 路由資訊 console.log("router", router); console.log("route",route); ```

十三.路由守衛

``` // 路由守衛

router.beforeEach((to, from, next) => { console.log("to",to); console.log("from",from); next() })

```

十四.生命週期

選項式 API 的生命週期選項和組合式 API 之間的對映

  • ~~beforeCreate~~ -> 使用 setup()
  • ~~created~~ -> 使用 setup()
  • beforeMount -> onBeforeMount
  • mounted -> onMounted
  • beforeUpdate -> onBeforeUpdate
  • updated -> onUpdated
  • beforeUnmount -> onBeforeUnmount
  • unmounted -> onUnmounted
  • errorCaptured -> onErrorCaptured
  • renderTracked -> onRenderTracked
  • renderTriggered -> onRenderTriggered
  • activated -> onActivated
  • deactivated -> onDeactivated

十五.store

  • vuex

Vue3 中的Vuex不再提供輔助函式寫法,想要學習vuex的夥伴可以移步我這篇文章。vue進階之路:vuex五大核心概念,看完這篇文章就夠了。

  • Pinia、 vue3更加推薦的是pinia,2021年11月24日,尤大在 Twitter 上宣佈:Pinia 正式成為 Vue 官方的狀態庫,意味著 Pinia 就是 Vuex 5,讓我們全面擁抱pinia吧!

基礎使用流程 ``` //下載pinia

npm install pinia -S ```

``` //main.ts

import { createApp } from 'vue' import App from './App.vue' import router from './router/index.ts'

// 引入pinia import { createPinia } from 'pinia'

// 建立vue例項 const app=createApp(App)

// 建立 Pinia 例項 const pinia = createPinia()

// 註冊掛載到vue實列 app.use(router).use(pinia).mount('#app')

```

``` // store/index.ts

import { defineStore } from 'pinia' // 1. 定義容器、匯出容器 // 引數1:容器的ID,必須是唯一的,後面Pinia會把所有的容器掛載到根容器 // 引數2:一些選項物件,也就是state、getter和action // 返回值:一個函式,呼叫即可得到容器例項

export const useMainStore = defineStore('main',{ // 類似於Vue2元件中的data,用於儲存全域性狀態資料,但有兩個要求 // 1. 必須是函式,目的是為了在服務端渲染的時候避免交叉請求導致的資料狀態汙染 // 2. 必須是箭頭函式,這樣是為了更好的 TS 型別推導 state:()=>{ return { info:"hello,東東吖,我是Pinia" } }, getters:{}, actions:{} }) //元件內使用

```

state 中資料的解構訪問 ``` // store/index.ts import { defineStore } from 'pinia' // 1. 定義容器、匯出容器 // 引數1:容器的ID,必須是唯一的,後面Pinia會把所有的容器掛載到根容器 // 引數2:一些選項物件,也就是state、getter和action // 返回值:一個函式,呼叫即可得到容器例項

export const useMainStore = defineStore('main',{ // 類似於Vue2元件中的data,用於儲存全域性狀態資料,但有兩個要求 // 1. 必須是函式,目的是為了在服務端渲染的時候避免交叉請求導致的資料狀態汙染 // 2. 必須是箭頭函式,這樣是為了更好的 TS 型別推導 state:()=>{ return { info:"hello,東東吖,我是Pinia", count:10 } }, getters:{}, actions:{} }) //元件內使用

③ **state 中資料的修改方式(actions和元件中)** // 一般的修改

//通過actions修改 // store/index.ts

import { defineStore } from 'pinia' // 1. 定義容器、匯出容器 // 引數1:容器的ID,必須是唯一的,後面Pinia會把所有的容器掛載到根容器 // 引數2:一些選項物件,也就是state、getter和action // 返回值:一個函式,呼叫即可得到容器例項

export const useMainStore = defineStore('main',{ // 類似於Vue2元件中的data,用於儲存全域性狀態資料,但有兩個要求 // 1. 必須是函式,目的是為了在服務端渲染的時候避免交叉請求導致的資料狀態汙染 // 2. 必須是箭頭函式,這樣是為了更好的 TS 型別推導 state:()=>{ return { info:"hello,東東吖,我是Pinia", count:10 } }, getters:{},

// store/index.ts // 類似於vue2元件的methods,用於封裝業務邏輯,修改state // // 注意:不能使用箭頭函式來定義actions,因為箭頭函式繫結外部的this actions:{ changeState (){ this.count += 10 this.info = "actions修改資料" }, changeStates (num:number){ this.count += num + 2 this.info = "actions修改資料" } }

})

//元件內使用

```

getters 的使用 ``` // store/index.ts import { defineStore } from 'pinia' // 1. 定義容器、匯出容器 // 引數1:容器的ID,必須是唯一的,後面Pinia會把所有的容器掛載到根容器 // 引數2:一些選項物件,也就是state、getter和action // 返回值:一個函式,呼叫即可得到容器例項

export const useMainStore = defineStore('main',{ // 類似於Vue2元件中的data,用於儲存全域性狀態資料,但有兩個要求 // 1. 必須是函式,目的是為了在服務端渲染的時候避免交叉請求導致的資料狀態汙染 // 2. 必須是箭頭函式,這樣是為了更好的 TS 型別推導 state:()=>{ return { info:"hello,東東吖,我是Pinia", count:10 } },

// 類似於元件的computed,用來封裝計算屬性,具有快取的功能
getters:{
    // 函式接收一個可選引數:state狀態物件
   count10(state){
       return state.count += 10
   },
   count20(state){
       return this.count += 20
   },
   // 若使用this.count,則必須指明返回資料的型別
   count11():number{
       return this.count += 11
   }

},

// store/index.ts // 類似於vue2元件的methods,用於封裝業務邏輯,修改state // // 注意:不能使用箭頭函式來定義actions,因為箭頭函式繫結外部的this actions:{ changeState (){ this.count += 10 this.info = "actions修改資料" }, changeStates (num:number){ this.count += num + 2 this.info = "actions修改資料" } }

})

```

``` //元件內使用

```