gpt4 book ai didi

javascript - Vue JS 组件未捕获引用错误 : Vue is not defined

转载 作者:行者123 更新时间:2023-12-03 01:03:11 24 4
gpt4 key购买 nike

我是 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)
})

项目/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,我也会收到以下错误

enter image description here

最佳答案

看来您已将组件定义移至另一个文件。如果您移动到另一个文件,则不需要使用 Vue.component。您只需导出一个对象,其中包含您想要附加到组件的数据、方法等。在 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}
})

关于javascript - Vue JS 组件未捕获引用错误 : Vue is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52530510/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com