在vue项目中引入vue-router报错

vue-router文档介绍引入vue-router有两种方法:

clipboard.png

我使用第一种没有问题,当我使用第二种方法时,我不知道import代码应该写在哪个文件里面。运行的时候浏览器报错:import declarations may only appear at top level of a module

代码:

<!--index.html-->
<body>
<div id="app">
    <h1>Hello App!</h1>
    <p>
        <router-link to="/foo">Go to Foo</router-link>
        <router-link to="/bar">Go to Bar</router-link>
    </p>

    <router-view></router-view>
    <script src="router.js"></script>
</div>
</body>
// router.js
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);

const Foo = { template: '<div>Foo</div>'};
const Bar = { template: '<div>Bar</div>'};

const routes = [
    {path:'/foo',component:Foo},
    {path:'/bar',component:Bar}
];

const router = new VueRouter({
    routes  // abbr. 相当于 routes:routes
});

const app = new Vue({
    router
}).$mount('#app');

刚刚接触vue,对哪些代码应该放在哪些地方,如何拼接很模糊。上面这个问题,望明白的人给个指引。

阅读 9.6k
3 个回答

这个得去了解模块化工程了。import 语句浏览器不支持,需要用到webpack之类的构建工具

需要用webpack构建才可以用import,webpack会解析import语法。

推荐问题