Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

bootstrap form validation only works in nuxt.js after reloading page

im using bootstrap(normal bootstrap, not vue-bootstrap) with nuxt.js. i have a form which i would like to use the bootstrap form validation with.

looks like this: https://getbootstrap.com/docs/4.5/components/forms/#custom-styles

my form has the novalidate attribute and all the inputs are required. i also have a submit event and a prevent: form v-on:submit.prevent="formSubmit"

this is just the unmodified code from the bootstrap docs:

(function() {
    'use strict';
    window.addEventListener('load', function() {
      // Fetch all the forms we want to apply custom Bootstrap validation styles to
      var forms = document.getElementsByClassName('needs-validation');
      // Loop over them and prevent submission
      var validation = Array.prototype.filter.call(forms, function(form) {
        form.addEventListener('submit', function(event) {
          if (form.checkValidity() === false) {
            event.preventDefault();
            event.stopPropagation();
          }
          form.classList.add('was-validated');
        }, false);
      });
    }, false);
  })();

i have this in a file called bootstrap-form-validation.js inside the plugins folder.

then in nuxt.config.js:

plugins: [
    { src: '~/plugins/bootstrap-form-validation.js', mode: 'client' }
],

i also set it to only run client side as i use server side rendering and that crashes the site if its not set.

now the problem is when i initially go to the contact page and click the submit button with all the fields empty, nothing happens. i can log a message to the console but the form is not validated. i can refresh the page and then the validation works.

for now i use a solution from here: Reload page in vue just once in mounted

where i can do:

mounted(){
    if(localStorage.getItem('reload')){
      localStorage.removeItem('reload')
    } else {
      localStorage.setItem('reload', '1')
      location.reload();
    }
  }

to refresh the page first time you go to the route. this makes the form validation work correctly. though ideally it would just work right away without the need to forcefully reload the page.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...