Default value of custom Component v-model should be set for v-text-field

Help! I need to set a default value for a v-text-field in a custom component, but all my attempts to override the editedItem.color v-model have failed.

I work with Laravel PHP and could really use some assistance from my fellow developers here. I'm new to this job and I really don't want to mess up.

<div v-if="formState === 'create'">
  <v-text-field
    v-model="editedItem.color"
    :default="'#FF0000'"
    :value="'#FF0000'"
    :disabled="true"
    label="Color*"
   />
</div>

When it comes to data, here's what the custom component provides:

  data: () => ({
    formState: 'create',
    loading: false,
    items: [],
    editedItem: {},
    selectedItems: [],
  }),

This should be a simple task, setting a default value and sending it to the API. However, the v-model does not accept v-bind:value or v-bind:default.

As I am new to Vue and this is a Vuetify component, I'm struggling to make it work.

In essence, I need either to set the default value for 'create' mode as #FF0000 or manipulate the value from v-color-picker to only use the hex value without returning an array.

The main issue is that the color picker returns an array, but we need a single hex value.

Here is my implementation on the tags/index.vue page using the custom component:

Thanks for any help!


<template>
  <work-custom-table
    v-model="headers"
    :routes="routes"
    :title="title"
    settings-key="crud.table"
    sort-by="name"
    allow-merge
  >
    <template #item.preview="{ item }">
      <v-chip :color="item.color">{{ item.name }}</v-chip>
    </template>
    <template #form="{editedItem, formState}">
      <v-row>
        <v-col>
          <v-text-field
            v-model="editedItem.name"
            :disabled="formState === 'view'"
            :rules="[$rules.required]"
            label="Name*"
            hint="*Required"
          />
        </v-col>
      </v-row>

      <v-row>
        <v-col>
          <v-text-field
            v-model="editedItem.description"
            :disabled="formState === 'view'"
            :rules="[$rules.required]"
            label="Description"
          />
        </v-col>
      </v-row>

      <v-row>
        <v-col>
          <div v-if="formState === 'create'">
            <v-text-field
              v-model="editedItem.color"
              :disabled="true"
              label="Color*"
            />
          </div>
          <div v-else>
            <v-color-picker
              id="tag-color"
              v-model="editedItem.color"
              :default="'#FF0000'"
              :disabled="formState === 'view'"
              class="elevation-0"
              label="Color*"
              hint="*Required"
              mode="hexa"
              hide-canvas
            />
          </div>
        </v-col>
      </v-row>
    </template>
  </work-custom-table>
</template>

Answer №1

<v-text-field> is essentially a wrapper for the HTML <input> element.

When working with <input> elements in Vue, the v-model and value attributes are mutually exclusive. The value attribute is only used when two-way data binding is not in place (using v-model).

All you need to do is set the default value in the editedItem itself before passing it to the <v-text-input> (and remove default and value). For example:

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: () => ({
    formState: 'create',
    editedItem: {
      color: '#FF0000'
    }
  })
})
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfd9d0d1cbff8a91c7">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2a4a7b7a6bbb4ab92e0fcaa">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ccbab9a98cfee2b4">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aadcdfcfdec3ccd3ea9884d2">[email protected]</a>/dist/vuetify.js"></script>

<div id="app">
  <div v-if="formState === 'create'">
    <v-text-field v-model="editedItem.color" :disabled="true" label="Color*" />
  </div>
</div>

If the editedItem is retrieved from another component or an external API, you will need to ensure the default value of color is set on it if it does not already have a truthy value. Here's a generic example:

methods: {
  getEditedItemFromApi() {
    this.$http.get('some/api/url')
      .then(r => this.editedItem = ({ 
        ...r.data,
        color: r.data.color || '#FF0000'
      }));
 }
}

(In this example, we are adding the color property to the response data if it doesn't exist or is falsey, giving it the default value.)

In essence, the default value needs to be set on the property bound to v-model before passing it to the <input> element.


Refer to the Vue documentation on v-model for more information.


For more complex cases, you can use a computed property with set and get methods to map default values:

Vue.config.productionTip = false;
Vue.config.devtools = false;
new Vue({
  el: '#app',
  data: () => ({
    items: [
      { id: 'one', color: 'black' },
      { id: 'two' }
    ],
    selectedItem: null
  }),
  computed: {
    editingItem: {
      get() {
        return { ...this.selectedItem, color: this.selectedItem?.color || '#FF0000' };
      },
      set(item) {
        this.selectedItem = item;
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <select v-model="selectedItem">
    <option :value="null">Select item</option>
    <option v-for="item in items" :value="item">{{item.id}}</option>
  </select>
  <div class="flexer" v-if="selectedItem">
    <input v-model="editingItem.color" :disabled="true" />
    <span :style="{ borderColor: editingItem.color }" /> 
   </div>
   <pre v-html="{ selectedItem, editingItem }" />
</div>

This approach also covers scenarios where the data is passed as a prop from a parent component.

Answer №2

While my solution may not be directly related to VUE, it could be beneficial to someone facing a similar issue. I reached a point where I needed to explore alternative solutions to resolve the problem at hand.

The issue I encountered was that the color-picker returned an array during 'create', but a hex value during 'edit'. To address this inconsistency, I implemented a somewhat unconventional solution by initially setting a default color value, and then adjusting it during edit mode. Rather than manipulating vue variables with getters and setters, I leveraged my Laravel API FormRequest instance to manipulate the data before validation through the prepareForValidation() method.

Here's what I did:

protected function prepareForValidation(){
    if(gettype($this->color) == 'array'){
        $this->merge(['color' => $this->color['hex']]);
    }
}

This approach allowed me to identify and extract the value from an array if present. Unfortunately, I was unable to make the get and set methods work as intended in my scenario.

Thank you!

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

clicking on internal links in the bootstrap side menu causes it to jump

Im trying to add a side menu to a help page. The menu and internal links are functioning properly, but when clicked, the side menu partially goes behind the navbar. As a beginner, I'm not sure how to resolve this issue. Can someone offer some guidan ...

Vue fails to update the modelValue within a watch function

When emitting the update:modelValue event inside $watch, the modelValue does not get updated without passing it by props. How can I ensure that the modelValue is updated without explicitly passing it by props? Example of MyComponent: export default define ...

What is the best way to sort and organize this JSON data?

There is an array of JSON objects named events that contains fields such as eventId, eventName, and the date of the event. [{event1}, {event2}, {event3}]; The goal is to iterate through this array and filter out events that occur on the same day. The des ...

Adjusted position of the viewport if the DOM element containing the renderer is not located at the top of the display

I've come across an issue with a three.js scene within an Angular custom directive in the view. At the top, there's a navigation bar for switching between views (pretty standard so far). I set up a simple scene with a cube and basic camera rotati ...

Jquery plugin experiencing a malfunction

I am encountering an issue with my custom plugin as I am relatively new to this. My goal is to modify the properties of div elements on a webpage. Here is the JavaScript code I am using: (function($) { $.fn.changeDiv = function( options ) { var sett ...

Values in Vuex do not get updated by getters

I'm having trouble understanding the functionality of getters in Vuex. The issue arises when I log out the token and find that the state and localStorage are empty, but the getters still contain the old token value. In the created lifecycle hook, I ha ...

"Upon populating an object with Mongoose, the return value is an

Recently, I set up a mongo database and created a Post model that has a reference to the User by _id. I wanted to retrieve information about the posts a user has made, so I implemented a callback function within exec() while populating the selected User. H ...

Converting PHP variables to JavaScript using AJAX and XML communication

In order to gain a deeper understanding, I am determined to tackle this task without relying on jQuery. This means I am willing to reinvent the wheel in order to fully comprehend how it functions. My research has led me to believe that AJAX is the key to a ...

Tips for Establishing Communication Between Two Dynamic Canvas Elements

How do I establish communication between two animated canvas elements? I have created two HTML5 canvas animations using Adobe Animate CC. Both of these animations are placed on a single HTML page. I am able to call functions from within the animations and ...

"Encountering an issue with AJAX file upload displaying an error message for

Before I showcase my code, allow me to explain my objective. My goal is to create a page that updates a user's details in the database using AJAX. Initially, I successfully achieved this task. Subsequently, I wanted to enhance the functionality by inc ...

Process executes another process

Can anyone assist me with a JavaScript inquiry? I am curious if it is feasible to implement this: variable: { info1: 'info1', info2: 'info2', show: false, someNameFunction: functionWhichIWantRun(row) } So, after defining the var ...

What is the process of assigning data, in JSON format, from an HTML form to a variable?

I have the coding below in my abc.html file, which converts form data to JSON format: <body> <form enctype='application/json' method="POST" name="myForm"> <p><label>Company:</label> <input name=& ...

Using the swiper carousel on WordPress results in an unexpected horizontal scrolling issue

Running an Elementor website, I need to incorporate various image carousels within my post content. Initially, I created a template for each carousel using Elementor. However, I have now decided to switch to utilizing a shortcode that leverages Elementor&a ...

Repairing div after upward scrolling and maintaining its fixation after refreshing the page

I have encountered two issues with this particular example: One problem is that the fixed_header_bottom should stay fixed beneath the fixed_header_top when scrolling up, causing the fixed_header_middle to gradually disappear as you scroll up, or vice v ...

Tips for Retrieving Data from a Multi-Dimensional Array

I need help accessing the values in my array and assigning them to variables for later use. I have created an array and used the randomGo() function to generate a random number that corresponds to a pair of numbers within the array. My goal is to assign ...

Reactive property in the Vue composition API

Within a Vue 3 project that utilizes TypeScript, there are two properties named locale and content: <script setup lang="ts"> import { computed, ref } from 'vue' import { useI18n } from "vue-i18n" import { Landing, Local ...

Steps for integrating external components into Laravel 5.3 with VueJs Routes

I am currently working with Laravel 5.3 and utilizing the built-in VueJs components. At this point, my goal is to implement routes into my project. I have attempted to use the following code, but unfortunately, it is not functioning as expected. const No ...

Organizing a Vue.js SPA project: Implementing Vuex store and API calls efficiently

Here is how I have organized the structure of my Vue app: components/ article/ AppList.vue common/ AppObserver.vue NoSSR.vue layout/ AppFooter.vue AppHeader.vue ui/ AppButton. ...

Is it possible to update the CSS file of an external SVG file in real-time?

Is there a way for an SVG image to reference another CSS file? A webpage contains an SVG file. A button allows users to switch between classic colors and high contrast mode on the entire webpage, including the SVG image. Attempt w.css (white backgrou ...

How do I remove all elements from the Canvas in R3F?

I need a way to clear all models from the Canvas with just one click and then switch over to a new Canvas. I want to make sure that all items are removed from memory before making the change. Is there a way to accomplish this? return ( <div clas ...