1. 程式人生 > 實用技巧 >Vue3.0體驗 002

Vue3.0體驗 002

1.初始化專案

  • 安裝vue-cli3npm install -g @vue/cli
  • 建立專案vue create my-project
  • 專案中安裝 composition-apinpm install @vue/composition-api --save
  • main.js中通過 Vue.use() 進行安裝 composition-api
import Vue from 'vue'
import VueCompositionApi from '@vue/composition-api'

Vue.use(VueCompositionApi) 

2.setup

setup 函式會在 beforeCreate 之後、created 之前執行

setup有兩個引數setup(props,content){}

  • props 外接傳過來的引數
  • content 上下文物件,類似於this,可以呼叫很多vue2.0需要通過this訪問的屬性,類似於context.attrs、context.emit、context.refs...,所以setup裡面不能用this

setup優點:

原本一個元件我們要宣告data()、methods、created、mounted、wathch...一系列option,現在的操作只用在setup內部,更加簡潔,功能模組把狀態和方法等劃分在一起,更利於模組化。我們就不需要每建立一個,要重新寫各種option一遍。

3.ref && reactive

  • ref ref() 函式用來根據給定的值建立一個響應式的資料物件const count = ref(0),通過count.value來獲取值
  • reactive 建立響應式的資料物件, reactive的返回值類似於vue2.0的data()返回的響應式物件const state = reactive({ count: 0 }),通過state.count來獲取值

ref和reactive都是建立響應式,那為什麼要有兩種方式建立呢? vue的團隊是為了使api適用於不同的開發風格。舉個例子引數宣告(var x = 1,y=2 ) 和(var state = {x:1,y:2}),第一種直接宣告是ref的方式,第二種用個物件儲存是reactive的方式。

注意! reative定義的state,如果用了展開運算子…,展開之後就不再是響應了, 可以用…toRefs(state)的形式 轉成ref

4.isRef & toRefs

isRef()用來判斷某個值是否為ref()創建出來的物件

toRefs()函式可以將reactive()建立的響應式物件轉化成ref建立的,這個函式的主要應用場景:

setup() {
    // 定義響應式資料物件
    const state = reactive({
      count: 0
    }) // reative建立的響應式
    
    const _ref = ref(1) // ref建立的響應式

    return {
      // 將 state 上的每個屬性,都轉化為 ref 形式的響應式資料
      ...toRefs(state),
      _ref
    }
}

為什麼要這樣做呢? 因為reactive()建立的響應物件只能通過return state出去,而不能以展開物件{state}的方式出去。所以有多個要return的響應式物件時,就需要這個函式。所以一般建議直接用ref,簡潔明瞭

5. computed & watch

vue3.0的computed和watch都是放在setup函式裡面,通過宣告的方式來建立。

  • computed
setup(){
    const count = ref(1)
    const countAdd = computed(() => count.value + 1)
    return{
        count,
        countAdd
    }
}

  • watch
const count = ref(1)

watch(() => console.log(count.value))

6. lifeCycle Hooks

  • beforeCreate-> use setup()
  • created-> use setup()
  • beforeMount -> onBeforeMount
  • mounted -> onMounted
  • beforeUpdate -> onBeforeUpdate
  • updated -> onUpdated
  • beforeDestroy -> onBeforeUnmount
  • destroyed -> onUnmounted
  • errorCaptured -> onErrorCaptured

添加了兩個新的除錯鉤子

  • onRenderTracked
  • onRenderTriggered
export default {
  onRenderTriggered(e) {
    debugger
    // inspect which dependency is causing the component to re-render
  }
}

7.provide & inject

provide()inject()可以實現巢狀元件之間的資料傳遞。這兩個函式只能在setup()函式中使用。父級元件中使用provide()函式向下傳遞資料;子級元件中使用inject()獲取上層傳遞過來的資料。

父元件:

  setup() {
    const conut = ref(1)
    
    provide('count', count) // 傳遞給子元件count=1
    
  },

子元件:

  setup() {
    
    const count = inject('count') // 1

  },