use-to-refs-instead-of-plain-destructing.png
Шаблон кодуVue.js

Vue toRefs(): Preserve Reactivity When Destructuring reactive()

Plain destructuring of reactive() properties can disconnect the extracted values from the reactive object. toRefs() creates refs that remain linked to the original state.

reactive() makes an object reactive, but plain destructuring extracts the current property values into new local variables.

For primitive values, this can break the reactive connection. When you need destructuring while keeping that connection to the original state, use toRefs().

Use toRefs() Instead of Plain Destructuring

До
javascript
const state = reactive({    page: 1,    search: '',}); const { page, search } = state; state.page = 2; console.log(page); // 1
Після
javascript
const state = reactive({    page: 1,    search: '',}); const { page, search } = toRefs(state); state.page = 2; console.log(page.value); // 2

In the first version, page receives the number 1. It is now a separate local value, so changing state.page later does not update it.

toRefs(state) instead creates a ref for each property. That ref stays linked to the corresponding property on the original reactive object.

JAVASCRIPT - toRefs() stays linked to state
const state = reactive({    page: 1,    search: '',}); const { page, search } = toRefs(state); page.value = 3; console.log(state.page); // 3 state.search = 'vue'; console.log(search.value); // "vue"

Changing page.value updates state.page, while changing state.search is immediately reflected in search.value.

toRefs() therefore does not copy the state. It creates refs linked to properties of the reactive object.

In JavaScript, refs use .value. In Vue templates, refs are automatically unwrapped, so page or search can usually be used without .value.

When toRefs() Is Useful

  • you want to destructure several properties from reactive();
  • those properties must remain reactive;
  • a composable returns a reactive object and callers should be able to destructure its properties safely.

If you continue using state.page and state.search directly, there is no need to add toRefs().

Plain destructuring extracts values from reactive(). toRefs() gives you separate refs that remain connected to the original state.

#vue-js #vue-3 #composition-api #reactivity #to-refs #reactive #javascript

Схожі поради

vue-nexttick-wait-for-dom-instead-of-settimeout-tip.pngПорада
Переглянути пораду
#next-tick #vue-js #vue-3 #composition-api #dom #reactivity