首页 > 解决方案 > 在 Laravel 中使用 Vue 插件时出错:未知的自定义元素:

问题描述

我正在尝试在我的 Laravel 5.7 应用程序中使用Simplert Vue 插件,但出现以下错误:

[Vue 警告]:未知的自定义元素:- 您是否正确注册了组件?对于递归组件,请确保提供“名称”选项。

我的代码基于这个问题Vue.js 2- sweet alert package simplet not working

app.js 文件:

require('./bootstrap');
window.Vue = require('vue');

import Simplert from 'vue2-simplert-plugin'
require('vue2-simplert-plugin/dist/vue2-simplert-plugin.css')
Vue.use(Simplert)

const app = new Vue({
  el: '#app',
  data: {
    obj: {
      title: 'Alert Title',
      message: 'Alert Message',
      type: 'info',
      useConfirmBtn: true,
      customConfirmBtnText: 'OK'
    }
  },
  methods: {
    openSimplert () {
      this.$Simplert.open(this.obj)
    },
    closeSimplert () {
      this.$Simplert.close()
    }
  }
})

home.blade.php 模板:

@section('content')
  // ..
  <simplert></simplert>
  // ..

包.json:

"dependencies": {
    "vue2-simplert-plugin": "^0.5.3"
}

import Simplert from 'vue2-simplert-plugin'在 VSCode中,我的 app.js 文件中的以下行有一个提示:

找不到模块“vue2-simplert-plugin”的声明文件。'x/node_modules/vue2-simplert-plugin/dist/vue2-simplert-plugin.js' 隐含了一个 'any' 类型。

这可能是问题吗?

标签: laravelvue.js

解决方案


注册 Vue 组件时,您需要包含一个名称,如下所示:

export default {
        name: 'example-name',
        data() {
            return {
            }
        },

所以在你的情况下:

const app = new Vue({
  el: '#app',
  name: 'example-name'
  data: {
    obj: {
      title: 'Alert Title',
      message: 'Alert Message',
      type: 'info',
      useConfirmBtn: true,
      customConfirmBtnText: 'OK'
    }
  },
  methods: {
    openSimplert () {
      this.$Simplert.open(this.obj)
    },
    closeSimplert () {
      this.$Simplert.close()
    }
  }
})

或者

您应该在 resources->js->components 文件夹中创建一个文件,名为ExampleComponent.vue. 在此处放置所有模板代码('#app' div 应显示的内容)。

使用该文件,您应该包括:

<template>
    //code here...
</tempate>

<script>
    export default {
        name: 'example-component-name',
        data() {
            return {
                obj: {
                    title: 'Alert Title',
                    message: 'Alert Message',
                    type: 'info',
                    useConfirmBtn: true,
                    customConfirmBtnText: 'OK'
                }
            }
        },
        methods: {
            //methods here
        } 
    }
</script>

然后在您的 app.js 文件中,您需要做的就是:

require('./bootstrap');

import Simplert from 'vue2-simplert-plugin'
require('vue2-simplert-plugin/dist/vue2-simplert-plugin.css')
Vue.use(Simplert)

Vue.component('example-component-name',require('./components/ExampleComponent.vue').default);

这应该对您的情况有所帮助-让我知道:)


推荐阅读