LoginSignup
1
0

Vue3でtoRefs()関数を使う

Posted at

reactive()関数とtoRefs()関数

  • Vue3ではreactive()関数を使用することでオブジェクトをリアクティブにできる

    • リアクティブなオブジェクト=オブジェクトの値が変更されると、自動的に追跡し変更されるオブジェクト
    • ただし、リアクティブなオブジェクトにアクセスする時は.valueをつける必要がある
  • toRefs()関数は、リアクティブなオブジェクトを個別の参照(ref)に変換できる

    • アクセスする際に.valueが不要になる

以下の場合、userはリアクティブなオブジェクトのため、nameの値を取得したい場合はuse.name.valueのように.valueを使う必要がある。

const user = reactive({
  name: 'John Doe',
  age: 25
});

以下の場合はrefの参照になるため、.valueを使わず直接参照できる

const { name, age } = toRefs(user);

console.log(name.value); // 'John Doe'
console.log(age.value);  // 25
  • reactive関数を使用して作成されたオブジェクトを、toRefsを使用せずに分割する場合、個別のプロパティはリアクティブではなくなり、プロパティの値が変更されても自動的に再レンダリングされなくなる

分割代入について

  • JavaScriptの構文の一つで、配列やオブジェクトの要素を別々の変数に分割して代入する方法を分割代入という

以下のコードは、numbers配列の要素を [a, b, c, d, e] という変数に分割代入していて、配列の要素がそれぞれの変数に割り当てられ、値が表示されている

const numbers = [1, 2, 3, 4, 5];

const [a, b, c, d, e] = numbers;

console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
console.log(d); // 4
console.log(e); // 5

オブジェクトでも分割代入は可能

const person = {
  name: 'John Doe',
  age: 30,
  city: 'New York'
};

const { name, age, city } = person;

console.log(name); // 'John Doe'
console.log(age);  // 30
console.log(city); // 'New York'

リアクティブなオブジェクトを分割代入する場合に、リアクティブな状態を保ちたいのであれば、toRefs()を用いるようにする

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0