Why use ref for variables in vue3

In vue2, we generally use let to define variables, and const directly declares variables to assign values, but in Vue 3, we can use ref variables to define, for example:

let prompt = ref<string>('aaa')

Doing so has the following advantages:

  1. Responsive update : Variables defined using ref will be automatically updated responsively. When the variable changes, the related components will be automatically re-rendered. This makes it easier for developers to manage state and data, and reduces the amount of code required to manually manipulate the DOM.

  1. Type inference : ref can provide type hints when defining variables, so that some errors can be caught when writing code, and intelligent hints can be made in the editor.

  1. Access to original value : Variables defined using ref can access their original value through .value , which makes it easy for developers to use native APIs to deal with variables wrapped by ref objects. For example, when using the setTimeout function, you need to pass a function as a parameter. This function needs to access the variable wrapped by the ref object. In this case, you need to use ref.value to obtain the original value.

  1. Support asynchronous update : ref provides an auxiliary function Vue.nextTick for asynchronous update , which can execute the callback function before the next DOM update cycle, so as to ensure that related operations are correctly processed after the variable is updated.

To sum up, using ref to define variables can make the code more concise and manageable, with better type hints and asynchronous update support.

Guess you like

Origin blog.csdn.net/playboyanta123/article/details/129624498