The setup function

  • The Setup function is a new component option in Vue3 that serves as a starting point for composite apis in components
  • Setup cannot use this; this points to undefined
  • The setup function is executed only once when the component is initialized
  • The setup function is executed before the beforeCreate lifecycle hook is executed
/ / test
export default {
  setup () {
    console.log('Setup executes'.new Date().getTime())
    console.log(this)},beforeCreate() {
    console.log('beforeCreate executed 'new Date().getTime())
    console.log(this)}/ / the result
  // Setup executed 1622628190197 timestamp is not deceptive
  // The beforeCreate command is 1622628190207
}
Copy the code

Reactive function

Reactive is a function that receives an ordinary object, converts the object data into a reactive object and returns it

Use reactive functions first need to be raised from vue
import {reactive} from 'vue'
Call reactive in the setup function and pass in the object data

<script>
import { reactive } from 'vue'
export default {
  setup () {
    const state = reactive({
      name: 'cp'.age: 18
    })
    return{state}}} </script> use:<template>
  <div>{{ state.name }}</div>
  <div>{{ state.age }}</div>
  <button @click="state.name = 'pink'">Change the value</button>
</template>
Copy the code

Ref function

Ref is a function that takes an incoming simple type or complex type and returns a responsive, mutable ref object

//1. Using the ref function first needs to be drawn from vue
import {ref} from 'vue'
//2. Call ref in the setup function and pass the data (simple type or complex type)
<script>
import { ref } from 'vue'
export default {
  setup() {
    let money = ref(100)
    console.log(money.value) / / 100
    return {
      money
    }
  }
}
</script>
//3. The setup function returns the value of the ref call as an object
//4. Note: to use the ref result in the setup function, you need to access it through '. Value '
Copy the code
  • A ref function can take a value of a simple type and return a ref-responsive object that can be changed to compensate for the lack of simple type support in reactive functions
  • Both reactive and REF functions provide transformations of reactive data
  • One way to write this is to use reactive only if we know exactly what field names are inside the object to be transformed, otherwise use ref all the time to reduce the mental burden of choosing a syntax