2. Composition API(其它部分)

1) shallowReactive 与 shallowRef

  • shallowReactive : 只处理了对象内最外层属性的响应式(也就是浅响应式)

  • shallowRef: 只处理了value的响应式, 不进行对象的reactive处理

  • 什么时候用浅响应式呢?

    • 一般情况下使用ref和reactive即可
    • 如果有一个对象数据, 结构比较深, 但变化时只是外层属性变化 ===> shallowReactive
    • 如果有一个对象数据, 后面会产生新的对象来替换 ===> shallowRef
  1. <template>
  2. <h2>App</h2>
  3. <h3>m1: {{m1}}</h3>
  4. <h3>m2: {{m2}}</h3>
  5. <h3>m3: {{m3}}</h3>
  6. <h3>m4: {{m4}}</h3>
  7. <button @click="update">更新</button>
  8. </template>
  9. <script lang="ts">
  10. import { reactive, ref, shallowReactive, shallowRef } from 'vue'
  11. /*
  12. shallowReactive与shallowRef
  13. shallowReactive: 只处理了对象内最外层属性的响应式(也就是浅响应式)
  14. shallowRef: 只处理了value的响应式, 不进行对象的reactive处理
  15. 总结:
  16. reactive与ref实现的是深度响应式, 而shallowReactive与shallowRef是浅响应式
  17. 什么时候用浅响应式呢?
  18. 一般情况下使用ref和reactive即可,
  19. 如果有一个对象数据, 结构比较深, 但变化时只是外层属性变化 ===> shallowReactive
  20. 如果有一个对象数据, 后面会产生新的对象来替换 ===> shallowRef
  21. */
  22. export default {
  23. setup () {
  24. const m1 = reactive({a: 1, b: {c: 2}})
  25. const m2 = shallowReactive({a: 1, b: {c: 2}})
  26. const m3 = ref({a: 1, b: {c: 2}})
  27. const m4 = shallowRef({a: 1, b: {c: 2}})
  28. const update = () => {
  29. // m1.b.c += 1
  30. // m2.b.c += 1
  31. // m3.value.a += 1
  32. m4.value.a += 1
  33. }
  34. return {
  35. m1,
  36. m2,
  37. m3,
  38. m4,
  39. update,
  40. }
  41. }
  42. }
  43. </script>

2) readonly 与 shallowReadonly

  • readonly:

    • 深度只读数据
    • 获取一个对象 (响应式或纯对象) 或 ref 并返回原始代理的只读代理。
    • 只读代理是深层的:访问的任何嵌套 property 也是只读的。
  • shallowReadonly

    • 浅只读数据
    • 创建一个代理,使其自身的 property 为只读,但不执行嵌套对象的深度只读转换
  • 应用场景:

    • 在某些特定情况下, 我们可能不希望对数据进行更新的操作, 那就可以包装生成一个只读代理对象来读取数据, 而不能修改或删除
  1. <template>
  2. <h2>App</h2>
  3. <h3>{{state}}</h3>
  4. <button @click="update">更新</button>
  5. </template>
  6. <script lang="ts">
  7. import { reactive, readonly, shallowReadonly } from 'vue'
  8. /*
  9. readonly: 深度只读数据
  10. 获取一个对象 (响应式或纯对象) 或 ref 并返回原始代理的只读代理。
  11. 只读代理是深层的:访问的任何嵌套 property 也是只读的。
  12. shallowReadonly: 浅只读数据
  13. 创建一个代理,使其自身的 property 为只读,但不执行嵌套对象的深度只读转换
  14. 应用场景:
  15. 在某些特定情况下, 我们可能不希望对数据进行更新的操作, 那就可以包装生成一个只读代理对象来读取数据, 而不能修改或删除
  16. */
  17. export default {
  18. setup () {
  19. const state = reactive({
  20. a: 1,
  21. b: {
  22. c: 2
  23. }
  24. })
  25. // const rState1 = readonly(state)
  26. const rState2 = shallowReadonly(state)
  27. const update = () => {
  28. // rState1.a++ // error
  29. // rState1.b.c++ // error
  30. // rState2.a++ // error
  31. rState2.b.c++
  32. }
  33. return {
  34. state,
  35. update
  36. }
  37. }
  38. }
  39. </script>

3) toRaw 与 markRaw

  • toRaw

    • 返回由 reactive 或 readonly 方法转换成响应式代理的普通对象。
    • 这是一个还原方法,可用于临时读取,访问不会被代理/跟踪,写入时也不会触发界面更新。
  • markRaw

    • 标记一个对象,使其永远不会转换为代理。返回对象本身
    • 应用场景:

      • 有些值不应被设置为响应式的,例如复杂的第三方类实例或 Vue 组件对象。
      • 当渲染具有不可变数据源的大列表时,跳过代理转换可以提高性能。
  1. <template>
  2. <h2>{{state}}</h2>
  3. <button @click="testToRaw">测试toRaw</button>
  4. <button @click="testMarkRaw">测试markRaw</button>
  5. </template>
  6. <script lang="ts">
  7. /*
  8. toRaw: 得到reactive代理对象的目标数据对象
  9. */
  10. import {
  11. markRaw,
  12. reactive, toRaw,
  13. } from 'vue'
  14. export default {
  15. setup () {
  16. const state = reactive<any>({
  17. name: 'tom',
  18. age: 25,
  19. })
  20. const testToRaw = () => {
  21. const user = toRaw(state)
  22. user.age++ // 界面不会更新
  23. }
  24. const testMarkRaw = () => {
  25. const likes = ['a', 'b']
  26. // state.likes = likes
  27. state.likes = markRaw(likes) // likes数组就不再是响应式的了
  28. setTimeout(() => {
  29. state.likes[0] += '--'
  30. }, 1000)
  31. }
  32. return {
  33. state,
  34. testToRaw,
  35. testMarkRaw,
  36. }
  37. }
  38. }
  39. </script>

4) toRef

  • 为源响应式对象上的某个属性创建一个 ref对象, 二者内部操作的是同一个数据值, 更新时二者是同步的
  • 区别ref: 拷贝了一份新的数据值单独操作, 更新时相互不影响
  • 应用: 当要将 某个prop 的 ref 传递给复合函数时,toRef 很有用
  1. <template>
  2. <h2>App</h2>
  3. <p>{{state}}</p>
  4. <p>{{foo}}</p>
  5. <p>{{foo2}}</p>
  6. <button @click="update">更新</button>
  7. <Child :foo="foo"/>
  8. </template>
  9. <script lang="ts">
  10. /*
  11. toRef:
  12. 为源响应式对象上的某个属性创建一个 ref对象, 二者内部操作的是同一个数据值, 更新时二者是同步的
  13. 区别ref: 拷贝了一份新的数据值单独操作, 更新时相互不影响
  14. 应用: 当要将某个 prop 的 ref 传递给复合函数时,toRef 很有用
  15. */
  16. import {
  17. reactive,
  18. toRef,
  19. ref,
  20. } from 'vue'
  21. import Child from './Child.vue'
  22. export default {
  23. setup () {
  24. const state = reactive({
  25. foo: 1,
  26. bar: 2
  27. })
  28. const foo = toRef(state, 'foo')
  29. const foo2 = ref(state.foo)
  30. const update = () => {
  31. state.foo++
  32. // foo.value++
  33. // foo2.value++ // foo和state中的数据不会更新
  34. }
  35. return {
  36. state,
  37. foo,
  38. foo2,
  39. update,
  40. }
  41. },
  42. components: {
  43. Child
  44. }
  45. }
  46. </script>
  1. <template>
  2. <h2>Child</h2>
  3. <h3>{{foo}}</h3>
  4. <h3>{{length}}</h3>
  5. </template>
  6. <script lang="ts">
  7. import { computed, defineComponent, Ref, toRef } from 'vue'
  8. const component = defineComponent({
  9. props: {
  10. foo: {
  11. type: Number,
  12. require: true
  13. }
  14. },
  15. setup (props, context) {
  16. const length = useFeatureX(toRef(props, 'foo'))
  17. return {
  18. length
  19. }
  20. }
  21. })
  22. function useFeatureX(foo: Ref) {
  23. const lenth = computed(() => foo.value.length)
  24. return lenth
  25. }
  26. export default component
  27. </script>

5) customRef

  • 创建一个自定义的 ref,并对其依赖项跟踪和更新触发进行显式控制
  • 需求: 使用 customRef 实现 debounce 的示例
  1. <template>
  2. <h2>App</h2>
  3. <input v-model="keyword" placeholder="搜索关键字"/>
  4. <p>{{keyword}}</p>
  5. </template>
  6. <script lang="ts">
  7. /*
  8. customRef:
  9. 创建一个自定义的 ref,并对其依赖项跟踪和更新触发进行显式控制
  10. 需求:
  11. 使用 customRef 实现 debounce 的示例
  12. */
  13. import {
  14. ref,
  15. customRef
  16. } from 'vue'
  17. export default {
  18. setup () {
  19. const keyword = useDebouncedRef('', 500)
  20. console.log(keyword)
  21. return {
  22. keyword
  23. }
  24. },
  25. }
  26. /*
  27. 实现函数防抖的自定义ref
  28. */
  29. function useDebouncedRef<T>(value: T, delay = 200) {
  30. let timeout: number
  31. return customRef((track, trigger) => {
  32. return {
  33. get() {
  34. // 告诉Vue追踪数据
  35. track()
  36. return value
  37. },
  38. set(newValue: T) {
  39. clearTimeout(timeout)
  40. timeout = setTimeout(() => {
  41. value = newValue
  42. // 告诉Vue去触发界面更新
  43. trigger()
  44. }, delay)
  45. }
  46. }
  47. })
  48. }
  49. </script>

6) provide 与 inject

  • provide和inject提供依赖注入,功能类似 2.x 的provide/inject

  • 实现跨层级组件(祖孙)间通信

  1. <template>
  2. <h1>父组件</h1>
  3. <p>当前颜色: {{color}}</p>
  4. <button @click="color='red'">红</button>
  5. <button @click="color='yellow'">黄</button>
  6. <button @click="color='blue'">蓝</button>
  7. <hr>
  8. <Son />
  9. </template>
  10. <script lang="ts">
  11. import { provide, ref } from 'vue'
  12. /*
  13. - provide` 和 `inject` 提供依赖注入,功能类似 2.x 的 `provide/inject
  14. - 实现跨层级组件(祖孙)间通信
  15. */
  16. import Son from './Son.vue'
  17. export default {
  18. name: 'ProvideInject',
  19. components: {
  20. Son
  21. },
  22. setup() {
  23. const color = ref('red')
  24. provide('color', color)
  25. return {
  26. color
  27. }
  28. }
  29. }
  30. </script>
  1. <template>
  2. <div>
  3. <h2>子组件</h2>
  4. <hr>
  5. <GrandSon />
  6. </div>
  7. </template>
  8. <script lang="ts">
  9. import GrandSon from './GrandSon.vue'
  10. export default {
  11. components: {
  12. GrandSon
  13. },
  14. }
  15. </script>
  1. <template>
  2. <h3 :style="{color}">孙子组件: {{color}}</h3>
  3. </template>
  4. <script lang="ts">
  5. import { inject } from 'vue'
  6. export default {
  7. setup() {
  8. const color = inject('color')
  9. return {
  10. color
  11. }
  12. }
  13. }
  14. </script>

7) 响应式数据的判断

  • isRef: 检查一个值是否为一个 ref 对象
  • isReactive: 检查一个对象是否是由 reactive 创建的响应式代理
  • isReadonly: 检查一个对象是否是由 readonly 创建的只读代理
  • isProxy: 检查一个对象是否是由 reactive 或者 readonly 方法创建的代理