简体   繁体   中英

Materialize form not working in vue.js component

I'm new to vue.js and want to make a simple form using materializecss framework in a component, which requires this jQuery snippt to work:

  $(document).ready(function() {
    M.updateTextFields();
  });

The component is:

<template>  
  <div>
       <div class="row">
        <div class="input-field col s6">
          <input value="" id="first_name2" type="text" class="validate">
          <label class="active" for="first_name2">First Name</label>
        </div>
      </div>
  </div>
</template>

<script>

  $(document).ready(function() {
    M.updateTextFields();
  });
export default {
  name: 'Login',
  data: function () {
   //rest of the scripts

      }

</script>

<style>
</style>

And the App.vue:

<template>
  <div id="app">
        <head>
          <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
          <link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/css/materialize.css" rel="stylesheet">

            $(document).ready(function() {
    M.updateTextFields();
  });


        </head>
        <NavbarComp/>
        <div id="middle">
            <<router-view/>     
        </div>

        <FooterComp/>
  </div>
</template>

<script>
import NavbarComp from './components/Navbar.vue';
import FooterComp from './components/Footer.vue';
import Landing from './components/Landing.vue';
import Login from './components/Login.vue';
import Register from './components/Register.vue';

export default {
  name: 'app',
  components: {
    NavbarComp,
    Landing,
    FooterComp,
    Login,
    Register
  }
}
</script>

And main.js

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'

import Routes from './routes'

const router = new VueRouter({
    routes: Routes,
    mode: 'history'
});

Vue.use(VueRouter);

new Vue({
    router: router,
  render: h => h(App)
}).$mount('#app')

The problem is that where ever I put the jquery snippet, the form label overlaps the field and the nice jump effect does not work.

How can I fix this?

In your component definition you can do something like this to ensure you're calling the materialize function after the elements you're targeting have made it into the DOM.

mounted() {
  this.$nextTick(M.updateTextFields);
},

You can see the mounted event is triggered after the component template is injected into the DOM in this diagram . The $nextTick() call defers the execution of your materialize function until we've ensured Vue has updated the DOM with your elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM