首页 > 解决方案 > 使用 vue-js-modal 组件的问题

问题描述

我按照他们文档中有关如何使用该组件的说明进行操作,但是我得到了TypeError: show is not a function

在我的主 JS 文件(app.js)中,我添加了以下内容并使用 npm 添加到我的项目中

import VModal from 'vue-js-modal'
Vue.use(VModal)

文档指出我现在可以从应用程序中的任何位置调用模式,因此我创建了一个特定于页面的 JS 文件并包含以下内容以隐藏/显示name="hello-world"包含 vue、app.js 和页面特定配置文件的页面上的模式.js 文件。

export default {
    methods: {
        show() {
            this.$modal.show('hello-world');
        },
        hide() {
            this.$modal.hide('hello-world');
        }
    }
}

当我加载页面时,我看不到模态内容,但是当我单击链接时,<a href="#" @click.prevent="show">Modal</a>我收到有关 show 方法的错误TypeError: show is not a function

我正在使用 laravel mix 并验证所有内容都按预期编译。下面是我如何在个人资料页面上包含 JS 文件:

<script type='text/javascript' src='/assets/js/manifest.js?ver=5.2.3'></script>
<script type='text/javascript' src='/assets/js/vendor.js?ver=5.2.3'></script>
<script type='text/javascript' src='/assets/js/app.js?ver=1569678574'></script>
<script type='text/javascript' src='/assets/js/profile.js?ver=1569678574'></script>

我正在尝试“升级”我的 Vue 和 JavaScript 体验,以前我只是坚持编写 ES5,而我的 Vue 是在没有组件的情况下编写的,并且绑定到特定于页面的 Vue 实例,因此非常感谢任何帮助!

编辑

应用程序.js

window.Vue = require('vue');

require('./global/header.js');

Vue.component('tabs', require('./components/Tabs.vue'));
Vue.component('tab', require('./components/Tab.vue'));

import VModal from 'vue-js-modal'

Vue.use(VModal)


new Vue({
    el: '#app'
});

profile.js

export default {
    methods: {
        show() {
            this.$modal.show('hello-world');
        },
        hide() {
            this.$modal.hide('hello-world');
        }
    }
}

编译 profile.js 的 webpack.mix.js

mix
  .js("resources/js/pages/home.js", "assets/js/home.js")
  .js("resources/js/pages/teams.js", "assets/js/teams.js")
  .js('resources/js/pages/profile.js', 'assets/js/profile.js')

标签: vue.jsvuejs2modal-dialogvue-componentes6-modules

解决方案


该错误未指定它是 $modal.show() 函数还是未定义的 profile.js show() 函数。我怀疑这是您的 profile.js show() 函数,因为对于 vue-js-modal,看起来一切正常。

您需要将 profile.js 添加为 vue mixin ( https://vuejs.org/v2/guide/mixins.html ),以便将其功能添加到 vue 实例中。所以在你的 app.js 中添加:

import profile from '/assets/js/profile'
Vue.mixin(profile);

推荐阅读