Best practices for integrating Vuex with Vuelidation

Currently, I am developing a Vue front end for an application that necessitates storing all form data locally before sending it to the backend in case of any network connectivity issues. To achieve this, I am using Vuex to manage and retain all the necessary form data throughout the application, allowing it to be saved and retrieved from local storage as needed.

Another crucial aspect is form validation, for which my plan is to utilize the Vuelidate library. The documentation suggests that simply adding this.$v.touch() in the event function should enable me to use Vuelidate even without a v-model. However, after attempting this solution, it does not appear to be functioning as expected.

Below is an example of the code:

<template>
  <form>
    <input name="full-name" v-model="fullName" placeholder="Full Name" />
  </form>
</template>

<script>
  export default {
    name: "AForm"
    computed: {
      fullName: {
        get() { return this.$store.state.fullName }
        set(name) {
          this.$v.touch();
          this.$store.dispatch("updateFullName", name);
        },
      }
    },
    validations: {
      fullName: minLength(4);
    }
  }
</script>

Upon inspecting $v.fullName, I noticed that the value is simply showing as true. Furthermore, when examining the entire $v object, I observed that $anyDirty: false.

Codesandbox

Answer №1

Incorrect Validation Configuration

The validation configuration should follow this format:

export default {
  /**
   * Validation Config Format:
   *
   *   validations: {
   *     PROP_NAME: {
   *       RULE_NAME: RULE
   *     }
   *   }
   */
  validations: {
    //fullName: minLength(4), // AVOID THIS

    fullName: {
      minLength: minLength(4)
    }
  },
}

$touch

If you are using this.$v.touch(), please note that it should actually be this.$v.$touch(). In cases where the computed property only sets one prop, you should call $touch() specifically on that prop (e.g., $v.PROP_NAME.$touch()) after the prop has been changed through a Vuex action.

export default {
  computed: {
    fullName: {
      get() {
        return this.$store.state.fullName;
      },
      set(name) {
        //this.$v.touch() // AVOID DOING THIS

        this.$store.dispatch('updateFullName', name)
        this.$v.fullName.$touch()
      }
    }
  }
}

https://codesandbox.io/s/using-vuelidate-with-vuex-80842?fontsize=14&hidenavigation=1&module=%2Fsrc%2FApp.vue&theme=dark

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

Animating SVGs in Internet Explorer (IE)

I'm currently working on an animation project using SVG images and JS, but unfortunately, I've run into a roadblock with SVG animations not functioning correctly in Internet Explorer. Do you happen to know of any solutions that could make it work ...

Generating dynamic dropdown menus using data from a database with the help of PHP and Ajax technologies

I'm currently working on creating a dynamic dropdown menu that will be populated with data retrieved from a database. I've hit a roadblock in parsing the data from a multidimensional array sent by a PHP file. Here's a snippet of my code: Se ...

What is the process for determining the total of elements within an array?

Imagine you have the following array: const items = [ { "amount1": "100", "amount2": "50", "name": "ruud" }, { "amount1": "40", "amount2": "60", "name": "ted" } ] Your goal is to calculate the sum of all amount1 and amount ...

React TypeScript - creating a component with a defined interface and extra properties

I'm completely new to Typescript and I am having trouble with rendering a component and passing in an onClick function. How can I properly pass in an onClick function to the CarItem? It seems like it's treating onMenuClick as a property of ICar, ...

Creating a multi-filter gallery similar to the one found in WooCommerce or eCommerce platforms involves integrating various filters to allow

Looking for a dynamic multifilter gallery similar to WooCommerce/ecommerce product filters? We have three types of filter dropdowns: COLOR, SIZE, and SHAPE. For example, if you select color: red and green, size: small, and shape: round The filtering wil ...

What is the best way to target the nth-child() of a slotted element within a web component that utilizes multiple uniquely named slots?

I am struggling to select the second slotted item in a specific slot using slot[name=foo]::slotted(:nth-child(2)){, but it's not behaving as I anticipated. Even though the first foo slot is styled with green, the second one doesn't follow suit. ...

JavaScript Popup prompting user on page load with option to redirect to another page upon clicking

Can a JavaScript prompt box be created that redirects to a site when the user selects "yes" or "ok," but does nothing if "no" is selected? Also, can this prompt appear on page load? Thank you! UPDATE: Answer provided below. It turns out it's simpler ...

A guide on utilizing AngularJS to extract data from a webpage

I'm attempting to transfer the information from a specific page on my website and paste it into a file. I know how to post a sample text stored in a variable from Angular and save it in a file in the backend using Node Express, so writing a file isn&a ...

The Firebase JQuery .on method is incrementally updating individual values in an array instead of updating them all simultaneously

I am trying to update the values of the orders placed by users on the Corporate's page without a refresh. I have implemented the jQuery .on method for this purpose. However, the values are being returned one by one from the array created for the order ...

converting nested object structures in typescript

I'm trying to flatten a nested object in my Loopback and Typescript controller Here's the structure of my model : export class SampleModel { id: number; code: number; guide?: string; gradeData?: string; } Take a look at this example obj ...

Retrieving data from notifications without having to interact with them (using Firebase Cloud Messaging and React Native)

Currently, I am able to handle messages whether the app is open, minimized, or closed. However, how can I process a message if a user logs into the application without receiving a notification? useEffect(() => { messaging().setBackgroundMessageHa ...

Optimizing SEO with asynchronous image loading

I've been developing a custom middleman gem that allows for asynchronous loading of images, similar to the effect seen on Medium. Everything is functioning smoothly, but I'm uncertain about the impact on SEO. The image tag in question looks like ...

Displaying information in a table format

How do I capture the titles of 'th' and 'td' elements in Vue.js when the save button is clicked? Here's my HTML code snippet: <tr> <th>Himalayan Salajit (Pakistan Onl ...

Incorporating Mongoose Schema structures into my NextJS webpage

I am new to NextJS and seeking assistance with an issue I am facing. I have defined 2 Mongoose schemas and using one on my page without any problems. However, when I try to import the second schema, my page fails to render and throws an error. Regardless ...

Tips for customizing the appearance of a Link component while it is the active page in Next.js

I'm seeking advice on how to style an anchor component differently when it is active on a page. Here's the code I have so far: import Link from 'next/link'; import styled from 'styled-components'; const NavStyle = styled.nav` ...

Show various attachment file names using jQuery

Utilizing jQuery, I've implemented a script to extract the filename from a hidden field and then append it to the filename class in my HTML. filenameCache = $('#example-marketing-material-file-cache').val().replace(/^.*[\\\/ ...

One way to showcase a single piece of data without the need for looping is by utilizing the `

I am encountering an issue. Why does the insertAdjacentHTML("afterend") output keep looping? I only want to display "1" once, not repeatedly. var btn = document.getElementById("btnClick"); btn.addEventListener("click", function (e) { e.preventDefaul ...

Tips on successfully transferring row data that has been clicked or selected from one adjacent table to another table

Currently, I am facing a challenge with two tables that are positioned next to each other. My goal is to append a selected row from the first table to the second table. After successfully extracting data from the selected row and converting it into an arr ...

I am looking to incorporate a new "ID" column into my mui data grid table in ReactJS that will incrementally count from 0 to the total number of rows

When displaying data from an API in a datagrid table component with multiple columns, it is necessary to include a column for the ID which should have values ranging from 0 to the number of rows. Currently, the Object_id is being displayed in this cell. T ...

Populate an array using a callback function within an async.series operation

I have a callback function within 'async.series' that generates multiple values and creates various outputs from 'elements'. Is there a way to save these return values into an array using 'forEach'? async.series( { ...