我使用 vue-cli 创建了一个新项目 ' vue init webpack-simple my-app
' 命令。在那个全新的安装副本中,我试图在默认创建的 App.vue 组件中导入 vue-router。但它给了我一个错误:' Uncaught ReferenceError: Vue is not defined
'。如果我在 App.vue 中再次导入 vue,则该应用程序运行正常。但是我已经在main.js中导入了vue,为什么还要在App.js中再次导入呢?有什么办法可以使用从 main.js 导入的 vue?这是我的代码:
主要.js:
import Vue from 'vue'
import App from './App.vue'
new Vue({
el: '#app',
render: h => h(App)
})
应用程序.vue:
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
import Vue from 'vue'; //**why I need to import it again? I already imported it in main.js
import VueRouter from 'vue-router';
Vue.use(VueRouter);
import QuestionOne from './components/QuestionOneTemplate';
const routes = [
{ path: '/', name: 'QuestionOne', component: QuestionOne },
];
const router = new VueRouter({
routes
});
window.router = router;
export default {
router,
name: 'app',
data () {
return {
}
}
}
</script>
<style lang="scss">
</style>
最佳答案
Is there any way i can use the imported vue from main.js?
不,您需要在每个使用
Vue
的文件中导入它.进口/要求是事情如何联系起来的。请放心,每个导入将是相同的单例实例。您可以使用
this.$router
从 Vue 组件的 javascript 访问路由器。和 this.$route
无需导入,或在模板内,只需使用 $router
和 $route
不推荐,但你可以 在 main.js 中将 Vue 分配给一个全局,并在不导入的情况下使用该全局。
主文件
import Vue from 'vue';
global.MyVue = Vue
应用程序
import VueRouter from 'vue-router';
MyVue.use(VueRouter);
为什么
这就是 ES6 将事物联系起来的方式。考虑一下
wiring
.如果有 1 个以上的 Vue 库可用,链接器如何知道使用哪个?如果另一个库定义了一个名为 Vue 的变量或函数怎么办?也许一个 lib 使用它自己的内部 Vue 来处理事件总线或其他功能。其他想法
显式导入还使 IDE 自动完成和语法突出显示更好地工作。一些 IDE 可以自动添加导入,这让生活更轻松。
关于vuejs2 - 导入 vue-router 时显示 Vue 未定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52272900/