P粉2311124372023-08-28 18:04:31
There are some similarities between
ref
and reactive
in that they both provide a way to store data and allow the data to be reactive.
but:
High Level Difference:
const wrappedBoolean = reactive({ value: true })
Source: Vue Forum Discussion< /p>
Reaction formula
reactive
Gets the object and returns a reactive proxy
to the original object.
Example
import {ref, reactive} from "vue"; export default { name: "component", setup() { const title = ref("my cool title") const page = reactive({ contents: "meh?", number: 1, ads: [{ source: "google" }], filteredAds: computed(() => { return ads.filter(ad => ad.source === "google") }) }) return { page, title } } }
illustrate
In the above, whenever we want to change or access the properties of page
,
For example page.ads
, page.filteredAds
will be updated through the proxy.
P粉4821083102023-08-28 11:15:43
reactive()
Only accepts objects, not JS primitives (String, Boolean, Number, BigInt, Symbol, null, undefined) < /里>
ref()
Calling behind the scenes reactive()
reactive()
works on objects, and ref()
calls reactive()
, objects work on both ref()
has a .value
attribute for reassignment, reactive()
does not have this attribute, and therefore cannot be reassigned< /里>
ref()
When..
'string'
, true
, 23
, etc.) reactive()
When..
ref()
ref()
seems to be the way to go since it supports all object types and allows reassignment using .value
. ref()
is a good starting point, but as you get used to the API, you'll know that reactive()
has less overhead, and you may find it more capable Meet your needs.
ref()
Use caseFor primitives you will always use ref()
, but ref()
is useful for objects that need to be reallocated (such as arrays).
setup() { const blogPosts = ref([]); return { blogPosts }; } getBlogPosts() { this.blogPosts.value = await fetchBlogPosts(); }
The above reactive()
needs to reassign a property rather than the entire object.
setup() { const blog = reactive({ posts: [] }); return { blog }; } getBlogPosts() { this.blog.posts = await fetchBlogPosts(); }
reactive()
Use caseA good use case for reactive() is a set of primitives that belong together:
const person = reactive({ name: 'Albert', age: 30, isNinja: true, });
The above code feels more logical than the above code
const name = ref('Albert'); const age = ref(30); const isNinja = ref(true);
If you're still lost, this simple guide helped me: https://www.danvega.dev/blog/2020/02/12/vue3-ref-vs-reactive/
Use only arguments from ref()
: https://dev.to/ycmjason/thought-on-vue-3-composition-api-reactive-considered-harmful-j8c
reactive()
and ref()
and other important information exist in the Vue Composition API RFC: https://vuejs.org/guide/extras /composition-api-faq. html#why-composition-api