background

Continuing the previous four articles:

  • Vue3.0 – start with ToDoList (1)
  • Try vue3.0- understand the changes (2)
  • Vue 3.0-TyepScript Development Kit (3)
  • Vue3.0 – watch it and start drying (4)

You can actually develop VUe3.0 by yourself, but here is an introduction to the VUE composite API, there is not much stuff


setup

  • As an entry point for using the Composition API within components
  • Pass in parameters: props,{slot,emit,attr}
  • Timing: Create component instances => initialize props=> call setup (called before the beforeCreate hook)
  • The ref returned by setup is automatically untangled in the template, without writing.value
  • This is not available in the setup function
<span @click="addCount">{{count}}</span> </div> </template> //ts <script lang="ts"> import {ref} from 'vue' export default { name: 'demo', setup(props,{slot,emit,attr}){ const count = ref(0) const addCount = ()=>{ count.value++ } return {count,addCount} } } </script>Copy the code
  • Same logic JSX writing (Demo.vue component)

  • Same logic using render API (demo.vue component)

  • DefineComponent (Demo.ts component)

Responsive system API

  • Reactive and ref

    • Reactive receives a common object and returns a reactive proxy for that common object, similar to vue.Observable () 2.0.
    • Ref takes a parameter value and returns a responsive and mutable REF object

    • Print ref objects and Reactive objects

  • computed

Const count = ref(1) // You can also pass just one const plusOne = computed(() => count.value + 1) // Pass get or set attributes,  const plusOne = computed({ get: () => count.value + 1, set: (val) => { count.value = val - 1 }, })Copy the code
  • Readonly (passing in an object (reactive or normal) or ref and returning a read-only proxy for the original object)

  • watchEffect
    • Execute a function passed in immediately, trace its dependencies responsively, and re-run the function when its dependencies change.
    WatchEffect (() => console.log(count.value)) watchEffect(() => console.log(count))Copy the code
    • Can be introduced into option
      Interface WatchEffectOptions {// Set function to be synchronized or re-run before component update, default post flush? : 'pre' | 'post' | 'sync' / / onTrack and onTrigger option can be used for debugging a debugger. OnTrack is called when a reactive object property or a ref is tracked as a dependency. OnTrigger onTrack is called when a dependency change triggers a side effect. : (event: DebuggerEvent) => void onTrigger? : (event: DebuggerEvent) => void }Copy the code
    • Stop listening behavior and stop callbacks
    Const stop = watchEffect((onInvalidate) =>{console.log(count.value) onInvalidate(()=>{console.log('watchEffect ends ')}) }) stop() // StopCopy the code
  • watch
// Compared with watchEffect 1. Lazy callback 2. 3. Access the values before and after the listener state change 4. It will not be executed when initializedCopy the code

Lifecycle hook

2.0 3.0
beforeCreate Use the setup ()
created Use the setup ()
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeDestroy onBeforeUnmount
destroyed onUnmounted
errorCaptured onErrorCaptured

Dependency injection

Function is similar to 2.x provide/inject, which can only be invoked in setup

// Const themeRef = ref('dark') provide(ThemeSymbol, themeRef)  const theme = inject(ThemeSymbol, ref('light')) watchEffect(() => { console.log(`theme set to: ${theme.value}`) })Copy the code

Template refs

Similar to this.$refs in Vue2.0, but the usage has changed

//html <div class="demo" ref="demo"> <span @click="addCount">{{count}}--{{countObject.count}}</span> </div> //setup Const demo = ref(null) onMounted(()=>{// Can only be accessed after rendering initialization. console.log(demo.value) })Copy the code
/ / get the list of refs < div v - for = "(item, I) in the list" : ref = "el = > {divs [I] = el}" > {{item}} < / div >Copy the code

Responsive system Utils

  • IsRef and unref
//isRef checks if a value is a ref object. Unref = isRef(val)? Val. value: syntax sugar for valCopy the code
  • ToRef and toRefs

    In setup, props is passed as a parameter. The props cannot be obtained by deconstructing it or it will become unresponsive

// toRef can be used to create a ref const countObject = reactive({count:0}) const countinObject = ToRef (countObject,'count') // Props gets separate data and keeps it responsive const propsCount = toRef(props, 'count')Copy the code
ToRefs = reactive({foo: 1, bar: 1); toRefs = reactive({foo: 1, bar: 1); 2,}) const stateAsRefs = toRefs(state) /* stateAsRefs type is as follows: {foo: Ref<number>, bar: Ref<number>} */Copy the code
  • IsProxy, isReactive, isReadonly
IsProxy checks whether an object is a proxy created by Reactive or readonly. IsReactive checks whether an object is a reactive proxy created by Reactive. IsReadonly checks whether an object is a proxy created by Reactive Readonly Created read-only proxyCopy the code

Advanced responsive system API

  • CustomRef: Custom Refs that explicitly control dependency tracing and trigger responses

  • MarkRaw and shallowXX
//markRow and shallowXXX below these features only stay at the root level (i.e. the first layer of the object, no further impact) //1. MarkRaw: marks an object as "never turn into a responsive proxy", Function returns the object itself const foo = markRaw({}) console.log(isReactive(reactive(foo))) Const bar = reactive({foo}) console.log(isReactive(bar.foo)) ShallowReadonly: creates a shallow responsive proxy for an object's private (layer 1) properties // 4. ShallowRef: creates a ref // Note: Const foo = shallowRef({}) // Changing the pair will trigger the response foo.value = {} // But the newly assigned object will not become a responsive object IsReactive (foo.value) // false //5. ToRow returns ordinary objects that have been converted to reactive proxies by reactive or readonly methodsCopy the code

The last

Vue3.0 here is a taste of the difference is good, like the point of praise yo, slip slip!Github code address