Basic usage of Setup, ref, reactive, toRef, toRefs

Ref and Reactive

ref

Ref operates with the base data type xxx.value

<template>
  {{sum}}
</template>

<script>

import {ref} from 'vue';
export default {
  name: 'App',
  setup(){
    const sum=ref(99)
    console.log("sum",sum.value)
  return {
    sum
  }
 }
}
</script>
Copy the code

reactive

Reactive is used to respond to an object

<template>
  {{sum.age}}
  {{sum.name}}
</template>

<script>

import {reactive} from 'vue';
export default {
  name: 'App',
  setup(){
    const sum=reactive({
      name:"chen",
      age:23
    })
   
    console.log("sum",sum.age,sum.name)
  return {
    sum
  }
 }
}
</script>




Copy the code

toRefs

  1. Convert a reactive object to a normal object but its properties are still reactive
  2. Structures can be destroyed without losing responsiveness
  3. There are objects that have no responsive properties of their own
<template>
  {{foo}}
  {{bar}}

</template>

<script>

import {reactive,toRefs} from 'vue';
function  useFeatureX() {
   const state = reactive({
    foo: 1,
    bar: "hello"
  })
  
  return toRefs(state)
}
export default {
  name: 'App',
  setup(){
    const {foo,bar}=useFeatureX()
  
  
  return {
    foo,
    bar
  }
 }
}
</script>


Copy the code

ToRefs and toRef

Context (non-reactive) The parent component invokes the child component's methodsCopy the code

Attrs and slot slots differ in that one is converted to multiple ref and the other is converted to a single ref

const state = reactive({
  foo: 1.bar: 2
})

const fooRef = toRef(state, 'foo')

fooRef.value++
console.log(state.foo) / / 2

state.foo++
console.log(fooRef.value) / / 3
Copy the code

Use the setup

The values in props(responsive) need toRefs to be responsiveContext (non-reactive) Parent component calls child component methods attrs and slot slots