Detailed explanation of setup ref reactive toRefs function in vue3.0

The use of vue3 commonly used functions

  • setup Function usage can replace the data and method attributes in Vue2, and directly add logic to setup

  • ref The variables used by the function in temlate need to be wrapped in ref

  • The returned array and method can only be used in the template

  setup() {
    
    
    const girls = ref(["小红", "小英", "晓红"]);
    const selectGirl = ref("");
    const selectGirlFun = (index) => {
    
    
      selectGirl.value = girls.value[index];
    };
    return {
    
    
      girls,
      selectGirl,
      selectGirlFun,
    };
  },
  • reactiveThe usage of the function, its parameter is not a basic type, but an object, so you don't need to write in the method .value, and datayou can put it back at the same time
 setup() {
    
    
    const data = reactive({
    
    
      girls: ["a", "b", "c"],
      selectGirl: "",
      selectGirlFun: (index) => {
    
    
        console.log(1111)
        data.selectGirl = data.girls[index];
      },
    });


    return {
    
    
      data
    };
  },

But to write this way, you must templateadd it when using variables and methods data.. This obviously does not conform to the coding habits we developed.
We can think of deconstructing data using the ...expansion operator when returning , but after deconstruction, it becomes Ordinary variables, no longer have the ability to respond,
so we need to use the toRefs() function

  • toRefsFunction usage
setup() {
    
    
    const data = reactive({
    
    
      girls: ["a", "b", "c"],
      selectGirl: "",
      selectGirlFun: (index) => {
    
    
        console.log(1111)
        data.selectGirl = data.girls[index];
      },
    });
    const refData = toRefs(data);

    return {
    
    
      ...refData,
    };
  }

How to choose ref and reactive, both methods are ok, they can both generate responsive objects, personal choicereactive

Guess you like

Origin blog.csdn.net/pz1021/article/details/114261127