首页 > 解决方案 > 在 VueJS 项目中正确的 MaterializeCSS 初始化

问题描述

我尝试在使用 npm ( )创建的 VueJS 项目中不使用 jQuery来初始化 MaterializeCSS 框架vue init webpack projectname

从版本开始1.0.0-rc.2,Materialize 支持它自己的初始化,没有 jQuery,像这样:

  document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.collapsible');
    var instances = M.Collapsible.init(elems, options);
  });

但是通过这种方式,JS Materialize 组件只有在手动页面重新加载之后才能工作,并且当我打开一些组件并返回带有 Materialize 内容的组件时 - 它不起作用 - 我需要一直手动重新加载页面。

那么如何以正确的方式初始化 JS 组件呢?

标签: vue.jsmaterialize

解决方案


它对我有用,所以你可能想试试这个:

转到您的src/main.js文件并添加以下行(如果假设您正在使用npm):

import 'materialize-css/dist/js/materialize.min'

就个人而言,我使用M.AutoInit()在每个需要它们的 vue 组件上初始化 JS 组件的方式:

<template>
  <div class="componentName">
    <!-- Some HTML content -->
  </div>
</template>


<script>
  export default {
    name: 'componentName',

    data() {
      return {
        // Some values
      };
    },

    mounted() {
      M.AutoInit(); // That way, it is only initialized when the component is mounted
    }
  }
</script>


<style scoped>
  /* Some CSS */
</style>

使用M.AutoInit()

document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.collapsible');
    var instances = M.Collapsible.init(elems, options);
  });

mounted组件的功能内部将导致它们仅在完全安装时才被调用。


推荐阅读