Loading Vue bootstrap b-form-select initially triggers Vuelidate's $anyDirty to become true

My current issue arises from the input event triggering when I initially assign a value to the v-model. This data is fetched via an API, causing the form to be marked as dirty due to the change. However, this poses a problem in another component where the $v.$anyDirty flag needs to be true for a pop up message to appear asking if the user is sure they want to navigate away. Unfortunately, calling $v.reset() after the data loads doesn't resolve the issue.

Vue.use(vuelidate.default);
const { required } = window.validators;
new Vue({
  el: "#app",
  data: {
    todos: [],
    todo: ""
  },
  async created() {
    var data = await axios.get("https://jsonplaceholder.typicode.com/todos");
    this.todos = data.data.map(d => d.id);
    this.todo = this.todos[0];
    this.$v.$reset()
  },
  validations() {
    return {
      todo: { required }
    };
  }
});
<link href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b6964647f787f796a7b267d7e6e4b39253b253b267968253a3a">[email protected]</a>/dist/bootstrap-vue.css" rel="stylesheet"/>
<link href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="36545959424542445746760218071805">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="294b46465d5a5d5b4859045f5c4c691b07190719045b4a071818">[email protected]</a>/dist/bootstrap-vue.min.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="25535040494c4144514065150b120b11">[email protected]</a>/dist/validators.min.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4d3b38282124292c39280d7d637a6379">[email protected]</a>/dist/vuelidate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>



<div id='app'>
  <div class="row">
    <div class="col-md-4">
      <b-form-select v-model="$v.todo.$model" :options="todos"></b-form-select>
    </div>
    <div class="col-md-8">
      <code>
        $anyDirty: {{$v.$anyDirty}}
      </code>
    </div>
  </div>
</div>

Answer №1

There is an issue where $v.reset() is executed before vue renders, causing the input events to occur afterwards. This results in a stack trace like this:

load > set values > reset validation > render > input event

To resolve this, move the reset inside Vue.nextTick. This will change the order of execution to:

load > set values > render > input event > reset validation

Vue.use(vuelidate.default);
const {
  required
} = window.validators;
new Vue({
  el: "#app",
  data: {
    todos: [],
    todo: ""
  },
  async created() {
    var data = await axios.get("https://jsonplaceholder.typicode.com/todos");
    this.todos = data.data.map(d => d.id);
    this.todo = this.todos[0];
    Vue.nextTick(() => {
      this.$v.$reset()
    })
  },
  validations() {
    return {
      todo: {
        required
      }
    };
  }
});
<link href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b6d4d9d9c2c5c2c4d7c69bc0c3d3f684988698869bc4d5988787">[email protected]</a>/dist/bootstrap-vue.css" rel="stylesheet" />
<link href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2f4d40405b5c5b5d4e5f6f1b011e011c">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="264449495255525447560b5053436614081608160b5445081717">[email protected]</a>/dist/bootstrap-vue.min.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="087e7d6d64616c697c6d4838263f263c">[email protected]</a>/dist/validators.min.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0d6d5c5ccc9c4c1d4c5e0908e978e94">[email protected]</a>/dist/vuelidate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>



<div id='app'>
  <div class="row">
    <div class="col-md-4">
      <b-form-select v-model="$v.todo.$model" :options="todos"></b-form-select>
    </div>
    <div class="col-md-8">
      <code>
        $anyDirty: {{$v.$anyDirty}}
      </code>
    </div>
  </div>
</div>

Additionally, you can utilize this.$nextTick instead of Vue.nextTick

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 is the best method for accessing data values from HTML within a JavaScript function?

Greetings, I am relatively new to using jquery and ajax. Here is a snippet of my code: .html <li class="list-group-item"> <h2>Vocabulary</h2> <h4> <span class="label label-success">Like Name</span& ...

Exploring the differences between arrays and objects provided by users

I am working on a functionality that involves comparing user input with predefined usernames and passwords. Here is what I have so far: var sys = { users: [ {user: 'user1', pass: 'qwerty'}, {user: 'Ragnar&apos ...

Using media queries in JavaScript

I've been trying to figure out how to format these parameters: @media screen and (-webkit-min-device-pixel-ratio: 1.3), (min-resolution: 124.8dpi), (max-device-width: 550px) My goal is to create an if statement using the values above, structured lik ...

Unable to extract string using JavaScript function

When dynamically generating table rows (buttons) using JS-Ajax, I am facing an issue. The removeProduct function alerts when a numeric value is parsed, but it does not alert for a string. Can anyone assist me in resolving this problem? The problem lies in ...

Ways to showcase an alert or popup when clicking?

I am utilizing a date picker component from this site and have enabled the 'disablePast' prop to gray out past dates preventing selection. Is there a way to trigger an alert or popup when attempting to click on disabled days (past dates)? Any sug ...

Leverage Angular's constant feature in scenarios that extend beyond the

Even though it may not be recommended, I find it fascinating to use Angular services outside of the angular framework. One example is having .constant('APIprefix','/api') I am curious about how to access the value of APIprefix outside ...

Hide the menu by clicking anywhere outside the React component

I'm working on a menu component that needs to close when clicking anywhere on the page while open. Is there a method to achieve this without having to add an event listener to the document and check the event.target? Unfortunately, I cannot send the ...

What steps can I take to make sure that a sub component's props are refreshed properly?

I'm encountering an issue with RTK queries in my project. I have a parent component that contains a table component. When a refresh event occurs, such as deleting data, the parent component receives updated data and passes it down to the child compone ...

Is it possible to invoke JavaScript code from TypeScript?

I'm struggling with calling a JavaScript file from TypeScript. After resolving one import issue and adjusting the base function for tsc recognition, I'm now stuck on recognizing a declared function prototype in the JavaScript file. Although I ha ...

Ordering Algorithm in AJAX Grid

I have a specific requirement that I spotted on this website: Whenever a user clicks on the table header, the content should be sorted accordingly. I have successfully implemented this feature for tables with pre-set values. https://i.sstatic.net/7cebx.p ...

Creating a custom design for legends in Chart.js

I'm currently working on a project using chart.js and I'm trying to customize the label/legend styling for my chart. My goal is to replace the rectangular legend with a circular one. I've come across the suggestion of creating a custom legen ...

Vue Quasar Drawer Layout with Bottom Bar

Struggling to implement a footer in my q-drawer. Below is the template and component code I am currently using: <template> <q-layout view="hHh lpR fFf"> <q-header elevated> <q-toolbar> <q-btn flat de ...

Displaying images within a table using innerHTML (Javascript / Html)

Let's start off with some important details: I have a dynamic table that is being generated. The structure of the table is as follows: |item__ | price | category | category | category | category | picture | |chicken| $20 | _______ |_ ______ ...

Issue with displaying Angular variable on webpage is not happening as expected

It's been a challenging journey trying to self-teach myself Angular.js. Unfortunately, I've hit a frustrating roadblock - the variables just won't display properly on the webpage! <!DOCTYPE html> <html ng-app> <head> & ...

Stop the chaining of Firestore calls in VueJS

I have been diving into the tutorial at . However, I am encountering an issue with the following code snippet: signup() { fb.auth.createUserWithEmailAndPassword(this.signupForm.email, this.signupForm.password).then(user => { this.$store.com ...

External API data is shown in the browser console but appears as undefined on the page

Can you please lend me a helping hand? I am facing a critical issue while attempting to retrieve data from an external API using axios in NextJS (Reactjs)/TypeScript through getServerSideProps. The data fetching is successful, and the JSON is returned on t ...

What is the process for accessing a local .json file from a remote machine or folder?

I am currently working on a project that involves a .json file stored in my local folder. Along with the file, I have Javascript code in the same directory to access and read the values from the .json file. To open the file, this is the line of code I use: ...

Whenever I enter a narrative into my text box, it must interact with this API

Whenever I enter a story in the text box, it should trigger this API call: The retrieved data should be displayed in the browser. Currently, the API call is not being made. All the relevant code can be found in 'searchbar.js'. Could you please ...

AngularJS: Assigning a value to an element

I am facing the challenge of automating an iframe using Selenium Webdriver and need to input a value into a text box. Here is the HTML code: <input class="ng-pristine ng-empty ng-invalid ng-invalid-required ng-valid-maxlength ng-touched" id="name" typ ...

Issue encountered while sending a jQuery error to the server?

Utilizing jQuery ajax POST throughout my application, here's an example of an ajax post. The content type is determined by the data variable. Content Type could be either application/x-www-form-urlencoded; charset=UTF-8 or application/json; charset=ut ...