【问题标题】:Failed to mount component using vue-js-toggle-button使用 vue-js-toggle-button 挂载组件失败
【发布时间】:2026-01-08 18:40:01
【问题描述】:

我尝试将plugin 用于带有 Vue 2 的项目,但收到如下所示的 Vue 警告。

[Vue 警告]:无法挂载组件:模板或渲染函数没有 定义

vue 组件内部:

import ToggleButton from 'vue-js-toggle-button'
export default {
  components: { ToggleButton }
}

那么,

<toggle-button :value="true" :labels="{checked: 'Foo', unchecked: 'Bar'}"/>

该插件不是那么受欢迎,我们将不胜感激。

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    为了完整性(Vue SFC 类):

    src/main.ts:

    import Vue from 'vue';
    import ToggleButton from 'vue-js-toggle-button';
    
    Vue.use(ToggleButton);
    
    new Vue({
      ...
      render: h => h(App)
    }).$mount('#app');
    

    src/components/MyComponent.vue:

    <template>
      <toggle-button />
    </template>
    
    <script lang="ts">
    import { ... } from "vue-property-decorator";
    // do NOT import the component in here
    
    @Component({
      components: {
        // do NOT declare the component in here
      }
    })
    export default class MyComponent extends Vue {
    }
    </script>
    
    <style scoped lang="scss">
    </style>
    

    【讨论】:

      【解决方案2】:

      您不会将切换按钮导出到另一个组件中。你将它导入到任何你想使用它的组件中,然后告诉 Vue 用Vue.use(ToggleButton) 来使用它。然后您可以在组件的模板中使用它,然后导出整个组件!

      例如:

      <template>
        <toggle-button #someOfYourValues#></toggle-button>
      </template>
      

      在这里,您不会导入任何 ToggleButton!您只需将其用作组件内的标签!

      让我们转到所有 Vue 实例创建发生的主 js 文件。通常,它看起来类似于:

      <script>
        import Vue from 'vue'
        import ToggleButton from 'vue-js-toggle-button'
        Vue.use(ToggleButton)
      
        new Vue({
          el: #yourDivInTheBaseHTMLFile
          # some other stuff for your vue instance
        })
      </script>
      

      我在我自己当前的 Vue 项目中对其进行了测试,这是一个包含许多组件的待办事项列表。当您执行Vue.use() 时,它实际上可以在其中的每一个内部工作。 如果需要,我可以将您链接到该项目,以便您查看,但这个简单的解释应该可以做到;)

      【讨论】:

      • 啊哈!我试试看