search

Home  >  Q&A  >  body text

Ref vs. React in Vue 3?

<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粉743288436P粉743288436463 days ago499

reply all(2)I'll reply

  • P粉231112437

    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.

    reply
    0
  • P粉482108310

    P粉4821083102023-08-28 11:15:43

    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

    reply
    0
  • Cancelreply