[Vuejs]-How to make every object property reactive?

1๐Ÿ‘

โœ…

Use a builtin function toRefs

interface Dog {
  name: string;
  age: number;
}

const puppy: Dog = {
  name: 'Snoop',
  age: 2,
};

import {toRefs} from 'vue'

const puppyRefs = toRefs(puppy)
// const puppyRefs: ToRefs<Dog>

type Pure<T>={[K in keyof T]: T[K]}
type PuppyRefs = Pure<typeof puppyRefs>
// type PuppyRefs = {
//     name: Ref<string>;
//     age: Ref<number>;
// }
๐Ÿ‘คDimava

3๐Ÿ‘

You can use reactive(). https://vuejs.org/api/reactivity-core.html#reactive

const puppy = reactive({
  name: 'Snoop',
  age: 2,
});

// Accessible like,
console.log(puppy.name);

Typing

Doc: https://vuejs.org/guide/typescript/composition-api.html#typing-reactive

reactive() implicitly infers the type,

const puppy = reactive({
  name: 'Snoop',
  age: 2,
});

// puppy.name is string

can explicitly define as,

interface Dog {
  name: string;
  age: number;
}

const puppy: Dog = reactive({
  name: 'Snoop',
  age: 2,
});
๐Ÿ‘คBadPiggie

1๐Ÿ‘

Not a Vue expert but how about doing it manually?

<script setup  lang="ts">
import { ref, Ref } from 'vue'

function createReactiveRefs<T>(obj: T): { [K in keyof T]: Ref<T[K]> } {
  const reactiveRefs: any = {};

  for (const key in obj) {
    reactiveRefs[key] = ref(obj[key]);
  }

  return reactiveRefs;
}

interface Dog {
  name: string;
  age: number;
}

const puppy: Dog = {
  name: 'Snoop',
  age: 2,
};

const reactivePuppy = createReactiveRefs(puppy);
</script>

<template>
  {{ reactivePuppy.name.value }}
</template>
๐Ÿ‘คBehemoth

Leave a comment