Challenges when sending data to a component in Vue

I'm completely new to using Vue.

In one of my components, I have integrated a multiselect component. The issue I am facing is that although I pass a value to my component and then pass it on to the multiselect, most of the time I cannot see that value reflected. Occasionally, after saving the code and re-running npm, I do get to see the result, but this seems to happen rarely.

Here is the template section of my component:

<template>
  <div>
     <multiselect
       :value="defaultValue"
       v-model="value"
       ...
     </multiselect>
  </div>
</template>

The script portion includes:

props: [some other things, "defaultValue"],
data() {
    return {
      value: this.defaultValue,
    }
  },

And I pass the prop like this:

<MyComponent other things... :defaultValue="station"/>

Currently, the output looks like this: https://i.sstatic.net/UcPMf.png

This is the desired outcome when the page loads: https://i.sstatic.net/6MfLq.png

What could be causing this problem?

Edit: When I pass v-model="defaultValue" to my multiselect, it does work. However, in doing so, I lose the ability to modify the value since props are immutable in Vue.

Answer №1

It is essential to assign a default value to defaultvalue in your component, and there are two possible approaches:

Firstly, you can pass a non-null value from the parent component.

Alternatively,

You can utilize the watch method to track changes in defaultvalue. If it is empty, assign a default value to defaultvalue.

For the parent component:

<multi-select :default-value="selectValue" />
data() {
  return {
   selectValue: '', // set as null, '' or '1', '3', '2'
  };
}

For the child component:

<select v-model="selectValue">
   <option
     v-for="(item, index) in selectArray"
     :key="index"
     :value="item.value"
   >
   {{ item.label }}
   </option>
</select>
export default {
  name: 'MultiSelect',
  props: {
    defaultValue: String,
  },
  data() {
    return {
      selectArray: [
        { value: '1', label: 'Value 1' },
        { value: '2', label: 'Value 2' },
        { value: '3', label: 'Value 3' },
      ],
    };
  },
  computed: {
    selectValue: {
      get() {
        if (!this.defaultValue) {
          return '1';
        }
        return this.defaultValue
      },
      set(newVal) {
        console.log(newVal);
      },
    },
  },
}

Answer №2

Avoid using both v-model and :value simultaneously

These two directives are conflicting with each other as they attempt to control the same underlying functionality.

Troubleshooting

I noticed your comment mentioning that using only v-model doesn't solve the issue.

To troubleshoot, modify your code to display some debugging details:


  <template>
      <div>
         <p>defaultValue is: {{defaultValue}}</p>
         <p>value is: {{value}}</p>
         <multiselect
           v-model="value"
           ...
         </multiselect>
      </div>
  </template>

It's crucial to understand that we currently lack information about the values being passed into this component through this.defaultValue.

For instance, consider the following:

<MyComponent other things... :defaultValue="station"/>

We cannot definitively determine the value of the variable this.station in your parent component, which may not align with the options available in the multiselect component.

The suggested debugging step will assist in resolving this uncertainty.

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

What is the best way to implement a loading cursor when the Submit button is clicked?

Is there a way to incorporate a progress cursor into my code in order to notify the user to wait when they click the Submit button or the Upload Button while uploading multiple files? Below is an example of my form: <form action="" method="post" enct ...

Setting up JW Player with a YouTube Embed URL

Embed link Is it possible to embed a YouTube link in my JW Player without disrupting the design? I have a specific design for the JW Player frame that I need to retain while incorporating the YouTube link. I have searched extensively but haven't foun ...

Node.js/Express - Guide on executing DELETE and PUT operations

I am seeking guidance on implementing the DELETE and PUT methods in a route for editing and deleting objects. How can I ensure that the browser sends the appropriate http requests when accessing specific objects? Is it necessary to modify the route to ma ...

Vue.js: How to Handle Web Page Updates When State Changes in Nested Objects

Vue.js offers methods like Vue.set for adding and Vue.delete for deleting, but there is no specific method for 'update'. Instead, you can use Object.assign. This works well unless there are changes in nested objects. Is there a function in Vue th ...

Currying in React - Understanding the Handler

Can anyone explain to me how this currying works in the example provided? I understand the name argument, but how does the event work in this scenario? <TextField placeholder="Name" InputLabelProps={{ shrink: true, ...

What factors contribute to the poorer performance of SVG rendering compared to PNG rendering?

I conducted a comparison of two images across various browsers. One image is an SVG while the other is a PNG format. Here are my findings: You can view the demo on JSFiddle here: http://jsfiddle.net/confile/2LL5M/ This is the code snippet I utilized: ...

To retrieve the request parameter within the socket.on operation

As a newcomer to node.js, I may have made some mistakes along the way. Please bear with me. When trying to retrieve parameters passed in the URL like localhost:3000?id=man&fm=gilli, I used the following code: app.get('/',function(req, re ...

Resource file for locating the mappings

As a beginner in sourcemapping, I have been tasked with saving the sourcemap in an external file. However, up to this point, I have only been able to concatenate the sourcemap to the minified .js file. What changes should I make to my approach? Am I miss ...

Chrome crashing due to toDataURL

Recently, I have been working on a Tile Renderer for three.js and so far, everything appears to be functioning correctly. The process is quite simple: a) It creates multiple cameras, b) Renders the scene using each camera c) Generates a 'toDataURL&a ...

Error with hyperlinks preventing redirection when clicking on the menu

$(document).ready(function () { $('.mobile-nav-button').on('click', function() { $( ".mobile-nav-button .mobile-nav-button__line:nth-of-type(1)" ).toggleClass( "mobile-nav-button__line--1"); $( ".mobile-nav ...

Divide data into an HTML table and merge it with header information

My HTML form contains an interactive HTML table where users can add/delete rows. I am sending this data to a Google Sheet and need to store the row information with corresponding header details. Each time a user submits the form, a new row is added to the ...

Need help adding color to your PlotlyJS barpolar chart background?

After creating a PlotlyJS barpolar chart, I noticed an issue with the background color where the bars end. The background color seems to be stuck on white, as shown in the image. (Please ignore the transparent black rounded square in the background, as it ...

The Best Way to Display Quad Wireframe in Three.js using OBJ Model

I am trying to display the wireframe of OBJ meshes using Three.js. However, Three.js can only render triangles, so I came up with the idea of creating a line for each edge of the model. After parsing the OBJ file and iterating through its vertices and fac ...

Is it possible to change the background color of the scrolling page?

Let's say I have 10 different sections, each with a unique background color assigned to them. As the user scrolls down from section 1 through 10, my goal is to dynamically change the body tag's background color based on which section is currentl ...

Twists and turns as I mix up Kineticjs

After scrambling my puzzle, I now need it to be rotated. Can anyone help me with this? Thanks :) fillPatternImage:imageObj, x:-pieceWidth*i/2, y:-pieceHeight*j/2, stroke: "#000000", ...

Receiving CORS response from the server for just one of the two API calls

Description of the issue: I am facing a peculiar problem where I am encountering different responses while making two calls to the same API. One call is successful, but the other returns a 504 error. Access to XMLHttpRequest at '' from orig ...

Stop event bubbling in Vue.js for router link

I'm working with the following HTML template... <template> <li class="nav-item" style="z-index:9"> <router-link :to="link.path" @click.native="linkClick" ...

In the Show Code feature of Storybook, every element is being displayed for

My Vue 3 + Storybook setup is all running smoothly, except for a little hiccup when I click "Show Code". It seems to display everything instead of just the template. Can anyone help me figure out what's going wrong? https://i.stack.imgur.com/zzBl0.pn ...

The bootstrap modal is appearing correctly, but the content within it is not displaying properly

I've been working on a website and added a modal for signup. However, when the user clicks on the signup button, the modal appears but the content inside it is not clickable. Can someone please help me with this issue? Here is the code snippet I am us ...

What is the best method for creating an HTML table using a Javascript function in PHP?

When working with a PHP file to generate a table based on SQL query results, I encountered an issue where only one incorrect row is returned. If anyone has a basic idea of what might be happening, it would be greatly appreciated. This is my HTML Code: &l ...