Is it advisable to modify the value of props by using toRef in the Composition API?

I've noticed a common practice in the CompositionAPI where props are converted to refs using `toRefs` function. This has left me feeling a bit confused.

For instance, citing the Vue 3 official guide:

export default {
  props: {
    user: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const { user } = toRefs(props)

    //... utilize the value of user
  }
}

I have two questions based on different scenarios:

  1. If the props.user is already reactive,
    and its value changes if modified in any ancestor component, then why do we need to use `toRefs`? Isn't it inherently reactive?

  2. On the other hand, if it's not reactive and just a basic string value,
    does converting it to a ref imply that we intend to alter its value? I understand that making an object reactive allows for its values to be changed. However, most guides and linters advise against modifying prop values directly (such as altering computed properties).

If I can directly modify the value of a prop within the component, then there might be no need to emit changes to the parent component continuously. This approach may seem convenient, but it raises questions about the appropriateness of modifying prop values once they become reactive.

Answer №1

When dealing with props in Vue, it's important to remember that they shouldn't be mutated. However, there are specific cases where you may need to pass a prop as an argument to a computed ref. This scenario is well explained in the documentation:

const { user } = toRefs(props)
// alternatively
// const user = computed(() => props.user)

someFunction(user);

This approach is particularly useful when a function requires a reference to the prop rather than just its value. For example:

function someFunction(val) {
  setTimeout(() => {
    console.log('Up-to-date value:', unref(val));
  }, 1000);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Selecting a particular item in a list depending on time using JavaScript, jQuery, or Angular

When working with a JSON file and binding it to list items, I have included a name/value pair in the json for each line indicating audio time, such as "time like 0, 5, 10 in seconds form". In my Cordova application, I am using a media plugin and implement ...

"Before the click even happens, the jquery click event is already

As I was developing a small todo app, I ran into an issue where the alert message seemed to pop up before the click event was triggered. It almost seems like the event is not registered properly. Can someone explain why this is happening? (function() { ...

How to Implement Click Actions on Elements in AngularJS

Just starting out with angularjs and I have a scenario with jQuery. handleClick(); function handleClick() { var doubleClick = false; $('#text span.word').on('click', function() { var that = this; setTimeout(funct ...

Having several contact forms embedded within a single webpage

I am currently in the process of developing a prototype website and my objective is to have multiple forms on a single page. My goal is to have a form for each service, where users can click on the service and fill out a form to request a quote. The first ...

Can someone please provide guidance on how to reset the value within a Q Select component in Quasar Framework

Currently, I am in the process of developing a Vue.js application using the innovative Quasar Framework. One challenge I face is resetting a q-form within my project. If you're interested in learning more about Quasar forms, here's a helpful re ...

Angular.js: how to filter an ng-repeat by a missing key/value pair

How can I filter the ng-repeat to only display rows where all key/value pairs are present? HTML <div ng-app="myApp" ng-controller="oneController"> <table class="table table-bordered table-hover"> <thead> <tr> <th> ...

Guide to automatically inserting text into an html form and submitting it without manual intervention

Currently, I am in the process of a project where my main goal is to design an HTML form for submitting replies. One interesting feature I want to include is an option for users who are feeling lazy to simply click on "auto-generate comment", which will ...

Is it possible to access the Firebase user object beyond the confines of the Firebase function?

Despite successfully logging users into my application using Google Auth from Firebase, I am facing an issue where the User object does not display on the front end of my application (which utilizes Pug templates). How can I resolve this? The code snippet ...

Add a new element to the page with a smooth fade-in animation using jQuery

var content = "<div id='blah'>Hello stuff here</div>" $("#mycontent").append(content).fadeIn(999); Unfortunately, the desired effect is not achieved with this code. I am trying to create a sleek animation when adding new content. ...

Oops! Looks like there's an issue with the rendering function or template in this component - it

After following the instructions in the tutorial at , I attempted to implement the example but encountered an issue that seems to be missing from the guide. const Vue = require('vue'); const server = require('express')(); const vssr = ...

Firestore data displaying as null values

Recently, I encountered CORS errors while polling the weather every 30 seconds in my program. Upon investigating, I discovered that the city and country were being interpreted as undefined. To fetch user data from my users' table, I utilize an Axios ...

Ways to target only the adjacent div

My goal is to target only the next div with the class name indented. Each indented div should have the same id as the <li> element right before it. Currently, I want each div with the class name indented to have the id of the previous <li>. He ...

Ensuring Image Loading in Vue Next: Tips for Verification

I am currently exploring how to determine if an image is loading in my project. I am using vite along with Vue Next (v3), however, I have not been able to find much information on this topic for Vue Next. I attempted using @load on the img element, but it ...

I've recently delved into the world of JavaScript and am currently working on creating a calculator website. However, I'm facing some challenges in getting it to function

I created a calculator code using HTML, CSS, and JavaScript for a website. However, due to my limited experience with JavaScript coding, I encountered some issues. Currently, I have only implemented the number input part (not operations or deletion), but w ...

Is it possible for Response.Redirect and OnBeforeUnload to cooperate effectively?

Is there a way to detect if the server-side code has sent a Response.Redirect in an OnBeforeUnload event? I need to alert the user before they navigate away from a page, but I don't want the prompt to appear when the server redirects. I'm dealin ...

Steps to retrieve the value of a particular row in a table using vuejs

Can you help me retrieve the value of a specific row in a table using VueJS 2? Here is an image of my current table: I need assistance with obtaining and displaying the last value from a loop in the "SHOW QR Button" within my code snippet. The button shou ...

What is the best way to substitute </br> and <br/> with in a text?

Is there a way to replace </br> and <br/> with \n functionally? There seems to be varied responses to this query. Errors are often made when writing the break tag. The solutions for both types of breaks mentioned above are detailed below ...

Why do I keep receiving the error message "Cannot set property of undefined"?

In the midst of a small project that involves utilizing nuxt, js, and axios, I encountered an issue when attempting to assign the response data to my formFields object. Despite having declared formFields within the data section, I kept receiving an error m ...

Struggling with converting 11-line toy neural network code into JavaScript

I'm preparing to deliver a brief presentation on neural networks this coming Tuesday to my fellow web developer students. My plan was to convert this code (found under Part 1, a tiny toy neural network: 2 layer network) into JavaScript so that it woul ...

What methods can I employ within an AngularJS controller to retrieve data from Google App Engine instead of solely relying on a JSON file?

As a newcomer to web development, I have been experimenting with retrieving data from a Google App Engine datastore and selectively displaying it on a webpage using AngularJS. While I have successfully integrated Angular with a JSON file and posted the con ...