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修改數據" } }

})

```

``` //組件內使用

```