Selecting default values from the Vuex store in Vue-Multiselect

Picture a Vuejs-Application equipped with Vuex. I am aiming to incorporate a mulitselect-dropdown. Here's a basic example inside the Vue-component:

<template>
  <div>
    <multiselect
      v-model="values"
      :options="options">
    </multiselect>
  </div>
</template>

<script>
  import Multiselect from 'vue-multiselect'
  export default {
    components: { Multiselect },
    data () {
      return {
        values: null,
        options: ['bar', 'foo', 'hello','test']
      }
    }
  }
</script>

<style src="vue-multiselect/dist/vue-multiselect.min.css"></style>

When I initialize "values" in data like this:

values: ["test"]

The multiselect-dropdown will show "test" as the already selected option. It can also be deselected by clicking and then reselected since it is part of the available options.

If I attempt to set my values as:

values:[this.$store.state.variableIwantPreselected]

It doesn't seem to work fully. In the selection-area/dropdown search field, those green boxes with the selected item names are usually displayed. However, instead of displaying the string that is stored in this.$store.state.variableIwantPreselected, only a small green box with no text appears.

I believe there might be something missing regarding Vuex and lifecycle hooks, but I haven't been able to pinpoint it yet.

Answer №1

When dealing with Vuex, it is recommended to utilize state, mutations, actions, and getters for efficient data manipulation in storage. For further insights on this topic, you can refer to this informative post

Answer №2

If you're facing similar challenges, remember to verify when your component is loaded/rendered. In my experience, it was loaded before the store value changed (which can occur when using vue-router with multiple components displaying on a single route).

The solution: delve deeper into the updated lifecycle hook.

Now, I trigger a function in the updated lifecycle hook. This function is defined within methods and checks if my values (initially empty list) have a length of 0. If they do, the store value is added to the list.

In the data section:

values: []

In the methods section:

checkValues() {
    if (this.values.length === 0) {
        this.values.push(this.$store.state.variableIwantPreselected)
    }
}

In the updated() method:

this.checkValues()

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

Adding over 20,000 rows to a table can be time-consuming, causing the page to become unresponsive once the process is complete

Looking at my table structure, it appears as follows: <tr ng-repeat="friend in friends | orderBy:predicate:reverse"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{f ...

Outdated JavaScript Alert

Is it possible to use JavaScript to create an alert message in my input field when a past date is selected? I would like the warning to say "past date, please enter a valid date." <html lang="en"> <head> <meta charset="U ...

Adjust the button's color even after it has been clicked

My goal is to update the button's color when it's clicked. I found some examples that helped me achieve this, but there's an issue - once I click anywhere outside of the button, the CSS class is removed. These buttons are part of a form, and ...

HTML generated in the header of a bootstrap-vue table

I'm currently developing a website using NuxtJS, Bootstrap Vue, and vue-i18n. Within the site, I have a table (<b-table>) that displays areas in square meters. The header of this table should show "sq m" in English and "m2" (m<sup>2</s ...

"Encountering an issue when attempting to load the vue-cookies module in

console.error node_modules/vue/dist/vue.runtime.common.dev.js:621 [Vue warn]: Error in mounted hook (Promise/async): "TypeError: Cannot read property 'get' of undefined" found in ---> <Anonymous> <Root> console.err ...

Device sending incorrect JSON format

A JSON response from a device is as follows: { "Order": ""3"", "ID": ""SHEET"", "Name": ""Time Sheet"", "ConID": ""!s?d2SzxcSDW1cf$*@4812sC#"" } The property values in the JSON are enclosed in double quotes, causing them to be incorrect. Is ...

How to pass the ng-repeat $index value as a parameter in AngularJS

Within the code snippet provided, there is a shell page index.html and a partial view currently utilized by two different controllers. The static data in AppController is connected to the list.html partial view and displayed as a table. In the JavaScript p ...

Guide to accessing a particular object key within an array by leveraging the MUI multiple autocomplete feature coupled with the useState hook

How can I retrieve the id key from a selected object in a given array list and set it to the state? You can find a sandbox example at this link: https://codesandbox.io/s/tags-material-demo-forked-ffuvg4?file=/demo.js ...

Preventing JSON data from being altered in AngularJS by creating a duplicate copy

It seems like there might be an issue with my implementation of AngularJS. I am trying to create a copy of a JSON object on page load, generate a form using the original data, and then compare the two JSON objects when the submit button is pressed to deter ...

"Troubleshooting: Why is my Bootstrap modal window only printing a

I've encountered an issue with printing the content of a Bootstrap modal window. Previously, the code I had was working fine but now it seems to be malfunctioning. Content is dynamically added to the form using appendChild() in a separate function. Ho ...

Securing API routes in Laravel

I have a Laravel application integrated with VUEJS for the front-end. I am retrieving data through API Routes. As an example, the route to fetch posts data is http://localhost/api/posts What would be the most effective method to secure my routes? After r ...

Encounters a fault while processing the php output

Displaying an error in the query The browser is showing the correct answer. $.ajax({ type: "POST", url: url, async: true, contentType: " charset=utf-8", dataType: "XMLHttpRequest", success: func ...

Update a Div automatically without causing it to scroll back to the beginning of the Div

I'm encountering an issue with a script on my website that refreshes a Div every 20 seconds. The problem is, after the refresh, it automatically scrolls to the top of the Div. I want it to remain at the last scroll position and not jump to the top. Ca ...

How can multiple arguments be passed to a function using JQuery's post method?

I can't seem to figure out how to pass multiple arguments to a function using jQuery's post method. It might sound like a silly question, but I'm struggling with it. Currently, my code looks something like this: $.post("<?php echo site_ ...

Defining the range of an array of numbers in TypeScript: A complete guide

When working with Next.js, I created a function component where I utilized the useState hook to declare a variable for storing an array of digits. Here is an example: const [digits, setDigits] = useState<number[]>(); I desire to define the range of ...

React TSX file not recognizing JSON data stored in an HTML data attribute

I am having some trouble with implementing the password toggle component from the Preline UI. Here is how the component looks: "use client" import React, { ChangeEvent, MouseEventHandler, useEffect } from "react"; export default functi ...

Firing a custom jQuery event when a page loaded via AJAX is complete, ensuring it is triggered

I am facing an issue with a particular scenario. There is a page that contains a script to load a child page and log a custom event, which is triggered in a Subform. --Index.html-- <body> <input type="button" class="clickable" value="Load child ...

Changes made to one order's information can impact the information of another order

Currently, I am in the process of developing a unique shopping cart feature where users input a number and a corresponding product is added to a display list. Users have the ability to adjust both the price and quantity of the products, with the total pric ...

using app.use to directly pass arguments without delay (NODE.JS)

I'm currently figuring out why the code 1 is functioning properly, while the code 2 is not... app.js: // Implementing Routes var server = require('./routes/server'); app.use('/', server); Route.js: var express = require(&a ...

Extracting Data from Multiple Pages Using Python 3 without Changing URL

Recently, I delved into the world of web scraping and decided to try my hand at grabbing data from various websites. Currently, I'm focused on scraping information from the site - Using selenium, I've managed to extract longitude and latitude da ...