Application of VUE 3

composition api-combined api

setup

  • parameter:

    props: Because of props is responsive, not deconstruction, if the deconstructing lose responsive, if necessary deconstruction prop, by using setupthe function of toRefsaccomplishes this

    import {
          
           toRefs } from 'vue'
    
    setup(props) {
          
          
    	const {
          
           title } = toRefs(props)
    
    	console.log(title.value)
    }
    

    context: is an ordinary js object, {attrs, slots, emit}, so it can be deconstructed

    export default {
          
          
      setup(props, context) {
          
          
        // Attribute (有状态、非响应式对象,不要解构)
        console.log(context.attrs)
    
        // 插槽 (有状态、非响应式对象,不要解构)
        console.log(context.slots)
    
        // 触发事件 (方法)
        console.log(context.emit)
      }
    }
    
  • Access component properties

    Execution setup, the component instance has not been created. Therefore, you can only access the following properties:

    • props
    • attrs
    • slots
    • emit

    In other words, you will not be able to access the following component options:

    • data
    • computed
    • methods
  • Use in combination with templates

    The returned object can be used directly in the template

  • this: no this

reactive

Packaging ordinary objects into responsive

ref function

Generate a responsive ref variable object => Create a responsive reference , and have a value attribute, the value of the variable is placed on the value attribute

// 生成
let name = ref('test')
// 在setup函数中返回该变量
// 模板中使用
{
    
    {
    
    name}}
// 修改变量值
name.value = 'world' // 注意一定是修改value属性

toRefs function

Lifecycle hook

Hook function used in setup

Option API Hook inside setup
beforeCreate Not needed*
created Not needed*
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeUnmount onBeforeUnmount
unmounted onUnmounted
errorCaptured onErrorCaptured
renderTracked onRenderTracked
renderTriggered onRenderTriggered

watch

import {
    
     ref, watch } from 'vue'
// 例子
const counter = ref(0)
watch(counter, (newValue, oldValue) => {
    
    
  console.log('The new counter value is: ' + counter.value)
})

// 语法
watch(一个响应式引用或者想要监听的getter,回调函数,配置选项)

computed

let cName = computed(_ => {
    
    
	return name.value+' computed'
})

Click me, VUE 3 official website

Guess you like

Origin blog.csdn.net/Menqq/article/details/113091880