vue3.0提前了解系列----一些高级的用法和api

大家好,首先先道个歉。有三个api还不太清楚是怎么回事。所以这次分享少分享三个API  事后等我搞清楚了我在增加上

欠三个api:

shallowReactive

shallowReadonly

shallowRef

 

这三个记录下,下面开始正题:

customRef

这个api是用来显式控制其依赖项跟踪和更新触发,这么说可能有人不理解,说简单点吧,就是你可以控制你视图更新时间,以及动态控制你动态处理设置值(比如后面增加一段话)

<p> 自定义ref : {{ testCustom }} </p>
<button @click = "getRef">
  获取ref值
</button>
<button @click = "setRef">
  设置ref值
</button>




import { customRef } from 'vue'
setup () {
    // 显式控制其依赖项跟踪和更新触发
    function customRefTest(value) {
      return customRef((track, trigger) => {
        return {
          get() {
            track()
            return value
          },
          set (newValue) {
            value = newValue + '自定义ref'
            setTimeout(() => {
              trigger()
            }, 10000)
          }
        }
      })
    }
    const testCustom = customRefTest(0)
    const getRef = () => {
      console.log(testCustom.value)
    }
    const setRef = () => {
      testCustom.value = '设置ref值'
    }
}

顺便贴一下官网的demo,一个节流的输入框双向数据绑定

<template>
  <div>
    <input v-model="text" />
    {{ text }}
  </div>
</template>
<script>
import { customRef } from 'vue'
function useDebouncedRef(value, delay = 200) {
  let timeout
  return customRef((track, trigger) => {
    return {
      get() {
        track()
        return value
      },
      set(newValue) {
        clearTimeout(timeout)
        timeout = setTimeout(() => {
          value = newValue
          trigger()
        }, delay)
      }
    }
  })
}

export default {
  setup() {
    return {
      text: useDebouncedRef('hello')
    }
  }
}
</script>
<style scoped>
  
</style>

markrow

标记对象,使其永远不会转换为代理。返回对象本身

{{ a }}
<button @click = "setFoo">
   设置foo值
</button>




import { markRaw, reactive, isReactive } from 'vue'
const foo = markRaw({
   a: 10
})
const state = reactive(foo)
console.log(isReactive(state)) // false
const setFoo = () => {
   state.a++
   console.log(foo)
}

注意,说明一下这里我点击这个button,视图是不会改变的,始终显示10。但是js中直接输出是最新的值

toRaw

返回一个代理对象(包含只读代理对象)的原对象,可用于临时读取,而不会触发代理访问和跟踪的一个开销。引用vue官网原话:返回反应或只读代理的原始对象。这是一个转义填充,可用于临时读取,而不会引起代理访问/跟踪开销或写入而不会触发更改。不建议保留对原始对象的持久引用。小心使用。

import { markRaw, reactive, toRaw }
const foo = markRaw({
  a: 10
})
const state = reactive(foo)
const toRawTest = reactive(fooTest)
const setShallowReactive = () => {
  console.log('toraw测试' + (toRaw(toRawTest) === fooTest)) // true
  console.log('toraw测试2' + (toRaw(state) === foo)) // true
}

 

render函数 && jsx

基本和vue2没什么太大区别,都是一样的用法,只不过不需要使用render函数,但是需要从vue中导入一个h

import { h, ref } from 'vue'
export default {
  setup() {
    const msg = ref(1)

    return () =>h('h1', [msg.value])
  }
}

 

至此,compositionapi所有用法已经基本可以告一段落,下一次为大家分享内容大概为:Fragments、Suspense以及Multiple v-models、和Portals组件,都是一些小用法的改变,请期待吧

posted @ 2020-05-10 22:07  金振宗  阅读(1265)  评论(1编辑  收藏  举报