What is the best way to make a Vuetify Select field with the "multiple" prop communicate with Axios data retrieved from a database?

As I am working on a project for a school district and learning Vue, I have successfully set up axios to interact with a MySQL database. However, I am facing an issue with the multiple prop on a v-select component. The problem lies in the data type mismatch - while the schools in the database are stored as Strings, v-select multiple requires an Array.

Within my Vuetify data table setup, there is a dialog for editing User's Information. One of the fields is for schools, where a user should be able to select multiple options. Here is the code snippet for that field:

<v-select
  :items='schools'
  v-model='schoolArray'
  label='School'
  multiple
  item-text='school'
></v-select>

Normally, 'editedItem.school' would be used as v-model, but since it returns a string and I need an array, I created a computed property to convert the school data into an array:

schoolArray (item) {
  return this.editedItem.school.split(',')
}

This adjustment helped display the schools from the database correctly, but it triggered an error message:

"[Vue warn]: Computed property "schoolArray" was assigned to but it has no setter."

To resolve this, I updated the computed property as follows:

schoolArray: {
  get: function () {
    var stringToArray = this.editedItem.school.slice(0).split(',')
    return stringToArray
  },
  set: function (school) {
    this.editedItem.school = school
  }
}

However, now I am encountering a new error:

'[Vue warn]: Error in render: "TypeError: this.editedItem.school.slice(...).split is not a function"'

I believe I may be overlooking something crucial in my understanding of Vue and Vuetify. If anyone could offer assistance or guidance, I would greatly appreciate it.

Answer №1

The issue arises from the fact that you are assigning an editedItem.school as an array, rather than a string. As a result, it raises an error when attempting to perform a split() operation on an array.

To resolve this problem, ensure that when setting the editedItem.school, you convert it back to a string using Array.join(",").

export default {
  data: () => ({
    schools: ["Schools 1", "Schools 2", "Schools 3"],
    editedItem: {...} 
  }),

  computed: {
    schoolArray: {
      get: function() {
        return this.editedItem.school.slice(0).split(",");
      },
      set: function(school) {
        // Convert it back to a string using `join(",")`
        this.editedItem.school = school.join(","); 
      }
    }
  }
}

Here's a demo example on codesandbox for reference.

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

Creating a Vertical Navbar Dropdown in Bootstrap 3.0 Without Appending to the Last List Item Only

Currently, I'm in the process of creating a panel layout that features an elegant vertical navbar. Although everything seems to be aligned correctly and I've managed to implement a dropdown menu in a vertical layout, it keeps appending to the las ...

What are the steps to deactivate data from a select option in Vue?

If a customer's status is marked as deceased, I need to prevent the selection of "healthy", "little healthy", and "unhealthy" options. How can I adjust the checkHealth method accordingly? <template v-for= "customer in customers"> < ...

Best practices for incorporating and leveraging node packages with Laravel Mix

As I embark on my Laravel (v 8.x) Mix project, I am encountering challenges when it comes to incorporating JavaScript from node modules. To kick things off, here is a snippet from my webpack.mix.js: mix.js('node_modules/mxgraph/javascript/mxClient.mi ...

Eliminating an ngRepeat item from the $rootScope array does not automatically result in the item being removed from the html code

Attempting to eliminate an li from a ul using angular. Although the element is successfully removed from the array, AngularJS does not remove the li until it is interacted with, such as being hovered over or clicked. See the code below: app.js myApp.run( ...

Is there a way to simulate a minified module for testing purposes?

For my project, I developed a component intended to function as a module. The implementation involves the utilization of third-party code provided in the form of a config file (initOpinionLab.js) and a .min.js file (opinionlab.min.js). As part of the devel ...

Display dynamic text from an input field in another div along with a checkbox

In the input field below, you can type something and then click the Add button. What will happen is that the text entered in the input field will be appended with a checkbox inside a div with the class .new-option-content. For a live example, check out th ...

Guide on embedding PHP/MYSQL array into an independent JavaScript document

I'm looking for guidance on how to insert an array from a PHP MySQL page into a separate JavaScript file. Can someone please help me with indicating where to include the PHP URL and provide the correct format for the PHP array code in order to achieve ...

Send the form after the asynchronous validator resolves its promise in AngularJS

My async validator 'username-validator' was designed to check for username availability without making multiple remote calls. To achieve this, I decided to update the ng-model on the 'blur' event rather than on every 'key press&apo ...

Using a function as a parameter in a jQuery Ajax Request URL

I am currently facing an issue while attempting to execute a function that generates the url utilized in a jQuery ajax POST request. It appears that the url parameter can solely be a string. Below is the code snippet, take note of the function within the u ...

What is the best way to eliminate additional values depending on the one I have chosen?

When utilizing the Vuetify v-autocomplete component with the multiple prop, we are able to select multiple values. How can I deselect other values based on the value I have selected? For instance: If I choose the main value, all others will be deselecte ...

Set the cookie to expire in 5 minutes using PHP, JavaScript, or jQuery

Is there a way to set a cookie in PHP that expires in 5 minutes? I am comfortable with the setcookie() function, but unsure about how to set the expiration time. Any explanation would be greatly appreciated. Could someone please guide me on how to achieve ...

Attempting to limit entry to a pathway when the loggedIn criterion is satisfied

I am currently facing a challenge with restricting access to the login page if the user is already logged in. I have been attempting to achieve this by checking for an existing token in the localStorage. Do you have any suggestions on how I can troublesh ...

Steps for creating a button that increments by using ng loop:1. Begin

I am attempting to create a button that can be used to increment and decrement. However, I am facing an issue where all input fields are being affected instead of just one. This is the code in body.component.html <div class="items-detail-detail" *n ...

Can you please explain the significance of the code "!!~this.roles.indexOf('*')" within the MEAN.io framework?

One particular line of code can be found in the startup file for the MEAN framework. if (!!~this.roles.indexOf('*')) { This specific line is located within the shouldRender function of the menus.client.service.js file, which resides in the publ ...

I'm attempting to make a specific element in an array shine in the designated order. What could be causing my code to not function as expected?

Currently, I am working on developing a Simon game. In order to make the divs glow in the sequence of the array used, I have implemented the glowInOrder() function. However, I am facing an issue where only the first div in the array glows, while the rest d ...

The shared service is experiencing difficulties in transferring data to the following component

I have developed two components along with a shared service. My goal is to transfer data from one component to another, but I am encountering an issue where the object appears empty. Below is the code for the first component: import { Component, OnInit } ...

What is the best way to show a specific object property that is nested in an array within a template attribute?

Encountering the following error message: TypeError: "someArr[0] is undefined". This issue arises when attempting to access an object property within a template: <th v-bind:data-id="someArr[0].id">{{someArr[0].name}}</th> Despite the erro ...

Using d3 in a Node project can lead to a jsdom error occurring

I'm feeling really lost with the current situation. When I try to use d3 version 2.10.1, the require 'd3' line triggers an error related to jsdom in the index.js file of d3: document = require("jsdom").jsdom("<html><head></he ...

Tips for integrating Grails ${createLink} into your javascript code

Below is a JavaScript function that I have: function GetSelectedItem() { var e = document.getElementById("country"); var strSel = e.options[e.selectedIndex].value; alert(strSel); var url = "${createLink(controller:'country', act ...

What is the best way to showcase information from multiple JSON files simultaneously?

Creating dynamic JSON URLs based on browser cookie data. var cookie = $.cookie('faved_posts'); The cookie contains IDs like 123456, 111111, 000001, etc. Now we need to request the JSON file for each ID in the cookie. We have: $.each(cookie, ...