Vue3 responsive setup uses this, ref, reactive, toRef, toRefs in detail

setup

setup() is where VUE3 writes a combined API. It is executed before creating components, so this cannot be used in it, and data in data(), methods in methods, and computed properties cannot be used in setup. data.

The properties that can be used in setup are: props, attrs, slots, emit, how to use? This depends on the two parameters of setup: props and context.

export default {
    
    
  props: {
    
    
    title: String
  },
  setup(props, context) {
    
    
  	const {
    
     title } = toRefs(props) //props是响应式的,不能使用 ES6 解构,需借助toRefs
  	const {
    
     attrs, slots, emit } = context //context可直接解构
    ...
  }
}

Responsive

Such as the total number of 30 people, 20 men, 10 women.
Create a reactive variable with ref(), and create a reactive object with reactive().
Access the value of ref: you need to use .value; you do not need to access the value of reactive. (No need for .value in the template: { { total }})

Please refer to the code for the usage of toRef and toRefs. Of course, it is not necessary to use them in the example. It is only for demonstration. If the responsive object catgory is inherited from the parent component, it will be very useful.

import {
    
     ref,reactive,toRef,toRefs } from 'vue'
export default {
    
    
  props: {
    
    
    title: String
  },
  setup(props, context) {
    
    
  	let total = ref(30) 
	total.value=50 //.value
	console.log(total.value) //50
	
	let catgory = reactive({
    
    male:20,female:10})
	catgory.male=40 //不用.value
	console.log(catgory.male) //40

	let male2 = toRef(catgory, 'male')  //toRef用响应式对象的属性新建一个新的ref,这个ref.value改变会同步改变原对象值 参数:(响应式对象,属性名)
	male2.value = 60 //toRef创建的是ref,所以要.value
	console.log(catgory.male) //60,说明原始对象的值也被改变
 	
 	let {
    
    male,female} = toRefs(catgory) //toRefs用解构的方式,把响应式对象的属性新建为多个新的ref
 	male.value=80
    female.value=20
    console.log(catgory.male) // 80,说明原始对象的值也被改变
    console.log(catgory.female)// 20,说明原始对象的值也被改变
  }
}

Guess you like

Origin blog.csdn.net/jeesr/article/details/120303154