【问题标题】:Vue JS Component Uncaught ReferenceError: Vue is not definedVue JS Component Uncaught ReferenceError: Vue is not defined
【发布时间】:2023-03-30 04:15:02
【问题描述】:

我是 vue js 的新手,我正在学习组件。我创建了一个包含组件的基本程序。以下是我的文件

项目/src/main.js

import Vue from 'vue'
window.Vue = Vue;

import ButtonCounter from './components/ButtonCounter.vue'

new Vue({
    el: '#components-demo',
    render: h => h(ButtonCounter)
})

project/src/components/ButtonCounter.vue

<template>
<div id="components-demo">
<button-counter></button-counter>
</div>
</template>

<script>
// Define a new component called button-counter
Vue.component('button-counter', {
  data: function () {
    return {
      count: 0
    }
  },
  template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})
</script>

当我执行这个时,我得到以下错误,即使我已经在 main.js 中全局声明了 Vue

【问题讨论】:

  • JS 模块是独立的代码块。所以如果你需要在模块中使用Vue,你必须在模块中导入它。

标签: javascript vue.js


【解决方案1】:

所以看起来您使用了组件定义并只是移动到另一个文件。如果您移动到另一个文件,则不需要使用Vue.component。您只需 export 一个对象,其中包含您想要附加到组件的数据、方法等。在Vue 实例中,您可以通过components 属性附加导入的组件。即

主索引.html

<div id="components-demo">
  <button-counter></button-counter>
</div>

组件.vue

<template>
  <button v-on:click="count++">You clicked me {{ count }} times.</button>
</template>

<script>
export default {
  data: function () {
    return {
      count: 0
    }
  }
})
</script>

然后在你的主文件中

import Vue from 'vue'
// window.Vue = Vue; -- don't need this anymore

import ButtonCounter from './components/ButtonCounter.vue'

new Vue({
    el: '#components-demo',
    render: h => h(ButtonCounter),
    components: {ButtonCounter}
})

【讨论】:

    【解决方案2】:

    错误在这一行

    window.Vue = Vue;
    

    只需导入并创建一个新的 Vue 实例

    import Vue from 'vue'
    import ButtonCounter from './components/ButtonCounter.vue'
    
    new Vue({
        el: '#components-demo',
        render: h => h(ButtonCounter)
    })
    

    【讨论】:

      猜你喜欢
      • 2020-05-05
      • 2021-06-16
      • 2016-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多