【Vuejs】865- 一篇文章上手Vue3中新增的API

1. 初始化項目

// ① npm i -g @vue/cli
// ② vue create my-project
// ③ npm install @vue/composition-api -S

// ④ main,js
import Vue from 'vue'
import VueCompositionApi from '@vue/composition-api'
Vue.use(VueCompositionApi)

2. setup方法

setup是vue3.x中新的操作組件屬性的方法,它是組件內部暴露出所有的屬性和方法的統一API。

2.1 執行時機

setup的執行時機在:beforeCreate 之後 created之前

setup(props, ctx) {
    console.log('setup')
  },
  beforeCreate() {
    console.log('beforeCreate')
  },
  created() {
    console.log('created')
  },

2.2 接受props數據
<!-- 組件傳值 -->
<com-setup p1="傳值給 com-setup"/>

// 通過 setup 函數的第一個形參,接收 props 數據:
setup(props) {
  console.log(props)
},
// 在 props 中定義當前組件允許外界傳遞過來的參數名稱:
props: {
    p1: String
}
/*
{}
p1: "傳值給 com-setup"
get p1: ƒ reactiveGetter()
set p1: ƒ reactiveSetter(newVal)
__proto__: Object
*/

2.3 context

setup 函數的第二個形參是一個上下文對象,這個上下文對象中包含了一些有用的屬性,這些屬性在 vue 2.x 中需要通過 this 才能訪問到,在 vue 3.x 中,它們的訪問方式如下:

setup(props, ctx) {
    console.log(ctx)
    console.log(this) // undefined
  },
/*
attrs: Object
emit: ƒ ()
listeners: Object
parent: VueComponent
refs: Object
root: Vue
...
*/

注意:在 setup() 函數中無法訪問到 this

3. reactive

reactive函數接收一個普通函數,返回一個響應式的數據對象。

reactive函數等價於 vue 2.x 中的 Vue.observable() 函數,vue 3.x 中提供了 reactive() 函數,用來創建響應式的數據對象,基本代碼示例如下:

<template>
  <div>
    <!-- 在 template 中訪問響應式數據 -->
    <p>當前的 count 值爲:{{count}}</p>
    <button @click="count += 1">+1</button>
  </div>
</template>

<script>
import {reactive} from '@vue/composition-api'
export default {
  setup(props, ctx) {
    // 創建響應式數據對象,得到的 state 類似於 vue 2.x 中 data() 返回的響應式對象
    const state = reactive({ count: 0 })
    state.count += 1
    console.log(state)
     // setup 函數中將響應式數據對象 return 出去,供 template 使用
    return state
  }
}
</script>

4. ref

ref() 函數用來根據給定的值創建一個響應式的數據對象,ref() 函數調用的返回值是一個對象,這個對象上只包含一個 .value 屬性:

<template>
  <div>
    <h3>02.ref.vue 文件</h3>
    <p>refCount:{{refCount}}</p>
    <button @click="refCount += 1">+1</button>
  </div>
</template>

<script>
import { ref } from '@vue/composition-api'
export default {
  setup() {
    // / 創建響應式數據對象 count,初始值爲 0
    const refCount = ref(0)
    // 如果要訪問 ref() 創建出來的響應式數據對象的值,必須通過 .value 屬性纔可以,只有在setup內部才需要 .value 屬性
    console.log(refCount.value) // 輸出 0
    // 讓 refCount 的值 +1
        refCount.value++
    // 再次打印 refCount 的值
        console.log(refCount.value) // 輸出 1
    return {
      refCount
    }
  }
}
</script>

4.1 在 reactive 對象中訪問 ref 創建的響應式數據

當把 ref() 創建出來的響應式數據對象,掛載到 reactive() 上時,會自動把響應式數據對象展開爲原始的值,不需通過 .value 就可以直接被訪問,例如:

setup() {
  const refCount = ref(0)
  const state = reactive({refCount})
  console.log(state.refCount) // 輸出 0
  state.refCount++ // 此處不需要通過 .value 就能直接訪問原始值
  console.log(refCount) // 輸出 1
  return {
    refCount
  }
}

注意:新的 ref 會覆蓋舊的 ref,示例代碼如下:

setup() {
  // 創建 ref 並掛載到 reactive 中
  const c1 = ref(0);
  const state = reactive({ c1 });

  // 再次創建 ref,命名爲 c2
  const c2 = ref(9);
  // 將 舊 ref c1 替換爲 新 ref c2
  state.c1 = c2;
  state.c1++;

  console.log(state.c1); // 輸出 10
  console.log(c2.value); // 輸出 10
  console.log(c1.value); // 輸出 0
}

5. isRef

isRef() 用來判斷某個值是否爲 ref() 創建出來的對象;應用場景:當需要展開某個可能爲 ref() 創建出來的值的時候,例如:

import { ref, reactive, isRef } from "@vue/composition-api";
export default {
  setup() {
    const unwrapped = isRef(foo) ? foo.value : foo
  }
};

6. toRefs

toRefs() 函數可以將 reactive() 創建出來的響應式對象,轉換爲普通的對象,只不過,這個對象上的每個屬性節點,都是 ref() 類型的響應式數據。

<template>
  <div>
    <h3>03.toRefs.vue文件</h3>
    <p>{{ count }} - {{ name }}</p>
    <button @click="count += 1">+1</button>
    <button @click="add">+1</button>
  </div>
</template>

<script>
import { reactive, toRefs } from "@vue/composition-api";
export default {
  setup() {
    // 響應式數據
    const state = reactive({ count: 0, name: "zs" });
    // 方法
    const add = () => {
      state.count += 1;
    };
    return {
      // 非響應式數據
      // ...state,
      // 響應式數據
      ...toRefs(state),
      add
    };
  }
};
</script>

7. computed計算屬性

7.1 只讀的計算屬性
<template>
  <div>
    <h3>04.computed.vue文件</h3>
    <p>refCount: {{refCount}}</p>
    <p>計算屬性的值computedCount : {{computedCount}}</p>
    <button @click="refCount++">refCount + 1</button>
        <!-- 點擊報錯 -->
    <button @click="computedCount++">計算屬性的值computedCount + 1</button>
  </div>
</template>

<script>
import { computed, ref } from '@vue/composition-api'
export default {
  setup() {
    const refCount = ref(1)
    // 只讀
    let computedCount = computed(() => refCount.value + 1)
    console.log(computedCount)
    return {
      refCount,
      computedCount
    }
  }
};
</script>

7.2 可讀可寫的計算屬性
<template>
  <div>
    <h3>04.computed.vue文件</h3>
    <p>refCount: {{refCount}}</p>
    <p>計算屬性的值computedCount : {{computedCount}}</p>
    <button @click="refCount++">refCount + 1</button>
  </div>
</template>

<script>
import { computed, ref } from '@vue/composition-api'
export default {
  setup() {
    const refCount = ref(1)
    // 可讀可寫
    let computedCount = computed({
      // 取值函數
      get: () => refCount.value + 1,
      // 賦值函數
      set: val => {
        refCount.value = refCount.value -5
      }
    })
    console.log(computedCount.value)
    // 爲計算屬性賦值的操作,會觸發 set 函數
    computedCount.value = 10
    console.log(computedCount.value)
    // 觸發 set 函數後,count 的值會被更新
    console.log(refCount.value)
    return {
      refCount,
      computedCount
    }
  }
};
</script>

8. watch

watch() 函數用來監視某些數據項的變化,從而觸發某些特定的操作,使用之前需要按需導入:

import { watch } from '@vue/composition-api'

8.1 基本用法
<template>
  <div>
    <h3>05.watch.vue文件</h3>
    <p>refCount: {{refCount}}</p>
  </div>
</template>

<script>
import { watch, ref } from '@vue/composition-api'
export default {
  setup() {
    const refCount = ref(100)
    // 定義 watch,只要 count 值變化,就會觸發 watch 回調
    // 組件在第一次創建的時候執行一次 watch
    watch(() => console.log(refCount.value), { lazy: false})
    setInterval(() => {
      refCount.value += 2
    }, 5000)
    return {
      refCount
    }
  }
};
</script>

8.2 監視數據源

監視 reactive 類型的數據源:

<template>
  <div>
    <h3>05.watch.vue文件</h3>
    <p>count: {{count}}</p> // 不是響應式數據
  </div>
</template>

<script>
import { watch, ref, reactive } from '@vue/composition-api'
export default {
  setup() {
    const state = reactive({count: 100})
    watch(
      // 監聽count
      () => state.count,
      // 如果變換 執行以下函數
      (newVal, oldVala) => {
        console.log(newVal, oldVala)
      },
      { lazy: true }
    )
    setInterval(() => {
      state.count += 2
    }, 5000)
    return state
  }
};
</script>

監視 ref 類型的數據源:

export default {
  setup() {
    // 定義數據源
    let count = ref(0);
    // 指定要監視的數據源
    watch(count, (count, prevCount) => {
      console.log(count, prevCount)
    })
    setInterval(() => {
      count.value += 2
    }, 2000)
    console.log(count.value)
    return {
      count
    }
  }
};

8.3 監聽多個數據源

監視 reactive 類型的數據源:

export default {
  setup() {
    const state = reactive({count: 100, name: 'houfei'})
    watch(
      // 監聽count name
      [() => state.count, () => state.name],
      // 如果變換 執行以下函數
      ([newCount, newName], [oldCount, oldName]) => {
        console.log(newCount, oldCount)
        console.log(newName, oldName)
      },
      { lazy: true} // 在 watch 被創建的時候,不執行回調函數中的代碼
    )
    setTimeout(() => {
      state.count += 2
      state.name = 'qweqweewq'
    }, 3000)
    return state
  }
};

監視 ref 類型的數據源:

export default {
  setup() {
    // 定義數據源
    const count = ref(10)
    const name = ref('zs')
    // 指定要監視的數據源
    watch(
      [count, name],
      ([newCount, newName], [oldCount, oldName]) => {
        console.log(newCount, oldCount)
        console.log(newName, oldName)
      },
      { lazy: true}
    )
    setInterval(() => {
      count.value += 2
    }, 2000)
    console.log(count.value)
    return {
      count
    }
  }
};

8.4 清除監視

在 setup() 函數內創建的 watch 監視,會在當前組件被銷燬的時候自動停止。如果想要明確地停止某個監視,可以調用 watch() 函數的返回值即可,語法如下:

<script>
// 創建監視,並得到 停止函數
const stop = watch(() => {
  /* ... */
})

// 調用停止函數,清除對應的監視
stop()

<template>
  <div>
    <!-- <h3>05.watch.vue文件</h3> -->
    <p>count: {{ count }}</p>
    <button @click="stopWatch">停止監聽</button>
  </div>
</template>

<script>
import { watch, ref, reactive } from "@vue/composition-api";
export default {
  setup() {
    // 定義數據源
    const count = ref(10)
    const name = ref('zs')
    // 指定要監視的數據源
    const stop = watch(
      [count, name],
      ([newCount, newName], [oldCount, oldName]) => {
        console.log(newCount, oldCount)
        console.log(newName, oldName)
      },
      { lazy: true}
    )
    setInterval(() => {
      count.value += 2
      name.value = 'houyue'
    }, 2000)
    // 停止監視
    const stopWatch = () => {
      console.log("停止監視,但是數據還在變化")
      stop()
    }
    console.log(count.value)
    return {
      stop,
      count,
      stopWatch
    }
  }
};

</script>

8.5 在watch中清除無效的異步任務

有時候,當被 watch 監視的值發生變化時,或 watch 本身被 stop 之後,我們期望能夠清除那些無效的異步任務,此時,watch 回調函數中提供了一個 cleanup registrator function 來執行清除的工作。這個清除函數會在如下情況下被調用:

watch 被重複執行了

watch 被強制 stop 了

Template 中的代碼示例如下:

<template>
  <div>
    <!-- <h3>05.watch.vue文件</h3> -->
    <input type="text" v-model="keywords" />
    <p>keywords:--- {{ keywords }}</p>
  </div>
</template>

Script 中的代碼示例如下:

<script>
import { watch, ref, reactive } from "@vue/composition-api";

export default {
  setup() {
    // 定義響應式數據 keywords
    const keywords = ref("");

    // 異步任務:打印用戶輸入的關鍵詞
    const asyncPrint = val => {
      // 延時 1 秒後打印
      return setTimeout(() => {
        console.log(val);
      }, 1000);
    };

    // 定義 watch 監聽
    watch(
      keywords,
      (keywords, prevKeywords, onCleanup) => {
        // 執行異步任務,並得到關閉異步任務的 timerId
        const timerId = asyncPrint(keywords);
        // 如果 watch 監聽被重複執行了,則會先清除上次未完成的異步任務
        onCleanup(() => clearTimeout(timerId));
      },
      // watch 剛被創建的時候不執行
      { lazy: true }
    );

    // 把 template 中需要的數據 return 出去
    return {
      keywords
    };
  }
};
</script>

9. provide & inject 組件傳值

provide() 和 inject() 可以實現嵌套組件之間的數據傳遞。這兩個函數只能在 setup() 函數中使用。父級組件中使用 provide() 函數向下傳遞數據;子級組件中使用 inject() 獲取上層傳遞過來的數據。

9.1 共享普通數據

app.vue 根組件:

<template>
  <div id="app">
    <h1>父組件</h1>
    <button @click="color = 'blue'">藍色</button>
    <button @click="color = 'red'">紅色</button>
    <button @click="color = 'yellow'">黃色</button>
    <son></son>
    <son></son>
  </div>
</template>

<script>
import { ref, provide } from '@vue/composition-api'
import Son from './components/06.son.vue'

export default {
  name: 'app',
  components: {
    'son': Son
  },
  setup() {
    const color = ref('green')
    provide('themecolor', color)
    return {
     color
    }
  }
}
</script>


06.son.vue son 組件:

<template>
  <div>
    <h3 :style="{color: color}">son 組件</h3>
    <grandson></grandson>
  </div>
</template>

<script>
import { inject } from '@vue/composition-api'
import Grandson from './07.grandson.vue'
export default {
    components: {
    'grandson': Grandson
  },
  setup() {
    const color = inject('themecolor')
    return {
     color
    }
  }
}
</script>

07.grandson.vue son 組件:

<template>
  <div>
    <h5 :style="{color: color}">grandson 組件</h5>
  </div>
</template>

<script>
import { inject } from '@vue/composition-api'
export default {
  setup() {
    const color = inject('themecolor')
    return {
      color
    }
  }
}
</script>

9.2 共享ref響應式數據

app.vue 根組件:

<template>
  <div id="app">
    <h1>父組件</h1>
    <son></son>
  </div>
</template>

<script>
import { provide } from '@vue/composition-api'
import Son from './components/06.son.vue'

export default {
  name: 'app',
  components: {
    'son': Son
  },
  setup() {
    provide('themecolor''red')
  }
}
</script>

06.son.vue son 組件:

<template>
  <div>
    <h3 :style="{color: color}">son 組件</h3>
    <grandson></grandson>
  </div>
</template>

<script>
import { inject } from '@vue/composition-api'
import Grandson from './07.grandson.vue'
export default {
    components: {
    'grandson': Grandson
  },
  setup() {
    const color = inject('themecolor')
    return {
      color
    }
  }
}
</script>

07.grandson.vue son 組件:

template>
  <div>
    <h5 :style="{color: color}">grandson 組件</h5>
  </div>
</template>

<script>
import { inject } from '@vue/composition-api'
export default {
  setup() {
    const color = inject('themecolor')
    return {
      color
    }
  }
}
</script>

10. 節點的引用 template ref

10.1 dom的引用
<template>
  <div>
    <h3 ref="h3Ref">TemplateRefOne</h3>
  </div>
</template>

<script>
import { ref, onMounted } from '@vue/composition-api'

export default {
  setup() {
    // 創建一個 DOM 引用
    const h3Ref = ref(null)

    // 在 DOM 首次加載完畢之後,才能獲取到元素的引用
    onMounted(() => {
      // 爲 dom 元素設置字體顏色
      // h3Ref.value 是原生DOM對象
      h3Ref.value.style.color = 'red'
    })

    // 把創建的引用 return 出去
    return {
      h3Ref
    }
  }
}
</script>

10.2 組件的引用

App父組件:

<template>
  <div id="app">
    <h1>父組件</h1>
    <button @click="showComRef">展示子組件的值</button>
    <son ref="comRef"></son>
  </div>
</template>

<script>

import Son from './components/06.son.vue'

export default {
  name: 'app',
  components: {
    'son': Son
  },
  setup() {
    const comRef = ref(null) 
    const showComRef = () => {
      console.log(comRef)
      console.log('str1的值是' + comRef.value.str1)
      comRef.value.setStr1()
    }
    return {
      comRef,
      showComRef
    }
  }
}
</script>

06.son.vue子組件:

<template>
  <div>
    <h3 :style="{color: color}">son 組件</h3>
    <p>{{str1}}</p>
  </div>
</template>

<script>
import { ref } from '@vue/composition-api'
export default {
  setup() {
    const str1 = ref('這是一個子組件!!')
    const setStr1 = () => {
      str1.value = '被賦值了'
    }
    return {
      str1,
      setStr1
    }
  }
}
</script>

11 nextTick

<template>
  <div>
    <h3>09.nextTick 組件</h3>
    <p>學習 $nextTick</p>
    <button v-if="isShowInput === false" @click="showInput">展示文本框</button>
    <input type="text" v-else ref="ipt">
  </div>
</template>

<script>
export default {
  data() {
    return {
      isShowInput: false
    }
  },
  methods: {
    showInput() {
      this.isShowInput = !this.isShowInput
      // console.log(this.$refs)
      this.$nextTick(() => {
        this.$refs.ipt.focus()
      })
    }
  }
}
</script>



   
   
   
  • 本文作者:liulongbin

  • 本文鏈接:http://www.liulongbin.top:8085/#/?id=_3-setup


1. JavaScript 重溫系列(22篇全)
2. ECMAScript 重溫系列(10篇全)
3. JavaScript設計模式 重溫系列(9篇全)
4.  正則 / 框架 / 算法等 重溫系列(16篇全)
5.  Webpack4 入門(上) ||  Webpack4 入門(下)
6.  MobX 入門(上)  ||   MobX 入門(下)
7. 100 +篇原創系列彙總

回覆“加羣”與大佬們一起交流學習~

點擊“閱讀原文”查看 100+ 篇原創文章

本文分享自微信公衆號 - 前端自習課(FE-study)。
如有侵權,請聯繫 [email protected] 刪除。
本文參與“OSC源創計劃”,歡迎正在閱讀的你也加入,一起分享。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章