Ref vs. React in Vue 3?
P粉743288436
P粉743288436 2023-08-27 20:35:30
0
2
454
<p>Check out some examples from some people's Vue 3 preview tutorials. [Currently in beta]</p> <p>I found two examples:</p> <h2>Reaction formula</h2> <pre class="brush:js;toolbar:false;"><template> <button @click="increment"> Count is: {{ state.count }}, double is: {{ state.double }} </button> </template> <script> import { reactive, computed } from 'vue' export default { setup() { const state = reactive({ count: 0, double: computed(() => state.count * 2) }) function increment() { state.count } return { state, increment } } } </script> </pre> <h2>Reference</h2> <pre class="brush:js;toolbar:false;"><template> <div> <h2 ref="titleRef">{{ formattedMoney }}</h2> <input v-model="delta" type="number"> <button @click="add">Add</button> </div> </template> <script> import { ref, computed, onMounted } from "vue"; export default { setup(props) { //State const money = ref(1); const delta = ref(1); // Refs const titleRef = ref(null); // Computed props const formattedMoney = computed(() => money.value.toFixed(2)); //Hooks onMounted(() => { console.log("titleRef", titleRef.value); }); // Methods const add = () => (money.value = Number(delta.value)); return { delta, money, titleRef, formattedMoney, add }; } }; </script> </pre> <p><br /></p>
P粉743288436
P粉743288436

reply all(2)
P粉231112437

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

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粉482108310

Points

  • reactive() Only accepts objects, not JS primitives (String, Boolean, Number, BigInt, Symbol, null, undefined)
  • ref() Calling behind the scenes reactive()
  • Since reactive() works on objects, and ref() calls reactive(), objects work on both
  • However, ref() has a .value attribute for reassignment, reactive() does not have this attribute, and therefore cannot be reassigned

use

ref() When..

  • It is a primitive (e.g. 'string', true, 23, etc.)
  • This is an object that you need to reallocate later (like an array - More info here)

reactive() When..

  • This is an object that does not need to be reallocated, and you want to avoid the overhead of ref()

Summarize

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 case

For 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 case

A 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);

Useful links

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

The decisions behind

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!