Setting a pre-selected value in a Vue.js dropdown list involves a few simple steps. This

Currently, I am developing two Vue components. I am sending array data from the parent component to the child component using props. Now, I have a requirement to pre-select a value in the dropdown list of the child component.

Below is a snippet of my code:

props:{
  // pre-selected value based on this.
  userdata:{
    type:[Array,Object],
    required:true,
  },
  roles:{
    type:[Array,Object],
    required:true,
  },

},

data(){
  return{
   mutableRoles:[],

  }
},

Here is the part of the code related to the view:

// I want to set a pre-selected value on this dropdown list
<select multiple v-model="mutableRoles" class="form-control">
         <option v-for="(role,index) in roles" v-bind:value="role.id" >{{role.name}}</option>
       </select>

I have come across many examples where only strings are used for pre-selection. However, in my case, both are arrays.

Answer №1

Check out this code example:

const UserRoles = Vue.component("user-roles", {
  template: `
    <div>
      <label>Choose a Role</label>
      <select v-model="roleId" @change="updateRole">
        <option v-for="role in roles" :key="role.id" :value="role.id">{{role.title}}</option>
      </select>
    </div>
  `,
  props: {
    userData: {
      type: [Array, Object],
      required: true,
    },
    roles: {
      type: [Array, Object],
      required: true,
    }
  },
  data: () => ({
    roleId: null
  }),
  methods: {
    updateRole() {
      this.userData.role = this.roles.find(r => r.id == this.roleId)
    },
  },
  mounted() {
    this.roleId = this.userData.role.id
  },
  watch: {
    userData(val) {
      if (val) this.roleId = val.role.id
    }
  }
})

new Vue({
  el: "#app",
  data: {
    rolesList: [{
      id: 1,
      title: "Admin"
    }, {
      id: 2,
      title: "User"
    }, {
      id: 3,
      title: "Guest"
    }],
    currentUser: {
      role: {
        id: 3,
        title: "Guest"
      }
    }
  },
  methods: {
    switchUser() {
      this.currentUser = {
        role: {
          id: 1,
          title: "Admin"
        }
      }
    }
  }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
  <p>Current User Role: {{currentUser}}</p>
  <user-roles :userData="currentUser" :roles="rolesList"></user-roles>
  <button @click="switchUser">Switch User</button>
</div>

The select element in this code example is suitable for primitive values, but you may need to add helper functions for more complex values.

If you encounter difficulties with this setup, consider using higher level Vue frameworks like vue-material, vuetify, element, or muse-ui which provide components with a higher level of abstraction to handle these situations.

UPDATE:

I have modified the code example to better align with your specific scenario.

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's the process for changing this arrow function into a regular function?

Hello from a child component in Vue.js. I am facing an issue while trying to pass data from the parent via sensorData. The problem lies in the fact that the arrow function used for data below is causing the binding not to occur as expected. Can anyone gu ...

Framer Motion causes a crash in a Next.js application with the error message: "Unable to find named export 'useId'"

I am encountering an error in my Next.js app that I can't seem to trace back to its source. Strangely, the code triggering the error is not something I wrote myself. error - file:///Users/cheq/Desktop/cheqo/node_modules/framer-motion/dist/es/component ...

What is the method for generating three inputs simultaneously in a single line?

I'm facing a challenge in my code where I want each line to contain only three input fields. Whenever I try to add a fourth input field, the first one remains on the previous line while the other three move to the next line. Oddly enough, this issue o ...

Exploring the Relationship Between jQuery and JSON through Iterating Over JSON Arrays

There is an array stored in a database: a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";} To manipulate this array, I first unserialize it using PHP and then encode it with JSON. The code snippet is as follows: $unwp = unserialize(&apos ...

javascript game for reversing an array

in case(po==true){ snake_array.reverse(); var i=0; var c=snake_array[i]; //drawing the head draw_head(c.x,c.y); for(i=1;i<snake_array.length;i++){ //drawing the body var c=snake_arr ...

Tips for removing residue from old watches

Our angularJS web components are integrated with a jqxGrid. Whenever a user makes edits in a cell, we implement a custom typeahead editor using Angular. However, I have noticed that after the editor is destroyed, my $watches array does not revert back to i ...

"Fixing VueJS axios issue: receiving 401 error for unauthorized POST request

I am having trouble sending a POST request with authorization to my REST api. Despite having CORS enabled on the server and everything working fine in Postman, I keep receiving an "unauthorized" error. Here is the code snippet I am using: axios . ...

Is it time to refresh the sibling element when it's selected, or is there

I have recently started working with react and TypeScript, and I am facing some challenges. My current task involves modifying the functionality to display subscriptions and transactions on separate pages instead of together on the same page. I want to sh ...

Retrieve the Latest Information from the Asp.Table

My table setup is as follows: <asp:Table ID="model" runat='server'> <asp:TableRow> <asp:TableHeaderCell class="col-xs-2"> Name </asp:TableHeaderCell> <asp:TableHeaderCell class="col- ...

How can I transfer information from Node.js to Vue in an Nuxt.js server-side rendering setup?

I need to find a way to pass Firestore data to Vue files from Node.js (Express) because I have to utilize Firestore's getCollections() method, which cannot be executed on the client side. I have set up nuxt-ssr for deploying Google Cloud Functions an ...

Retrieve the data entered in the submit button field

My question concerns a form with two buttons: <form method="post" action=""> <button type="submit" name="age" value="20">Age 20</button> <button type="submit" name="age" value="30">Age 30</button> </form> When ...

The incorrect value of variable V is being passed to the doSomethingWithData(v) function. This could lead to unexpected results

const Greetings = () => { const [num, setNum] = React.useState(1); React.useEffect(() => { setTimeout(async () => { await setNum(2); processData(num) }, 3000) }, []); retur ...

How can I add text to a textbox within a duplicated div using Javascript or Jquery?

I'm looking to add text to a cloned div's text box using jQuery. I have a div with a button and text box, and by cloning it, I want to dynamically insert text into the new div. $(document).ready(function () { $("#click").click(function () { ...

How can I store the status of checked and unchecked checkboxes in an array of objects using Angular 7?

I have a set of checkboxes with a parent-child structure, and their values are generated dynamically in a loop. When I click the submit button, I want to capture the selected or unselected values in the specified format (as shown in the commented output) ...

Should I refrain from storing user files on my server?

Greetings! I am currently working on an Express js + React js application and using MySQL for database management. I have successfully stored user information like email, hashed passwords, and user IDs in the database. However, now I want to create ...

Providing a public API that exclusively grants access to requests originating from my own website

After hours of scouring Google and SO, I have yet to find someone facing the same challenge I am encountering now. Here's the situation: We have invested a significant amount of money and effort into maintaining a database. The data from this databas ...

Unable to Retrieve Modified Content with $().text();

In the process of developing an app, I am encountering a challenge where I need to transfer user input to another element after processing it. However, I am facing an issue with accessing the updated value of the <textarea> using .text(), as it only ...

You are unable to assign mutations in Vuex

Dealing with a peculiar problem where "val" and "ok" can be used within "console.log()", but for some reason, state.user cannot be assigned any value. However, state.user does display 'ok' on the website. export const state = () => ({ user: ...

Trigger a functional component's function in React using Chrome developer tools

function App() { const myFunction = () => { console.log('hello world!') } return <div>...</div> } After the website has fully loaded and the component is mounted, can we access the JavaScript to call myFunction()? ...

Setting up Socket.io results in numerous transport polling GET requests being initiated

I have set up an express.js server-side and followed the socket.io guide. However, I am facing issues with the socket connection not being successful, and there seems to be a high number of unexpected GET requests like this: https://i.stack.imgur.com/GDGg ...