2016-11-26 111 views
1

我正在学习Vue,并开始使用the webpack template。我想要做的第一件事是添加对Vue路由器的支持,但是现在我已经花了几个小时而无法渲染单个路由(我总是以空白页面结束)。令人沮丧!如何使用Vue 2中的Vue路由器

我只想让一个.vue文件充当布局文件,将不同的.vue文件作为“页面”呈现到其中。有人能告诉我该怎么做吗?这是我最新的尝试失败:

main.js

import Vue from 'vue' 
import VueRouter from 'vue-router' 
import App from './App' 
import Home from './components/Home' 
import About from './components/About' 

Vue.use(VueRouter) 

const routes = [ 
    { path: '/', component: Home }, 
    { path: '/about', component: About } 
] 

const app = new Vue({ 
    router: new VueRouter({ 
     routes 
    }), 
    component: App 
}).$mount('#app') 

App.vue(布局文件)

<template> 
    <div id="app"> 
     <h1>Hello App!</h1> 
     <p> 
      <router-link to="/">Go to Foo</router-link> 
      <router-link to="/about">Go to Bar</router-link> 
     </p> 

     <router-view></router-view> 

    </div> 
</template> 

<script> 
    export default { 
    } 

</script> 

<style scoped> 

</style> 

组件/ About.vue(几乎相同的组件/主页。 vue)

<template> 
    <div> 
     <h1>About</h1> 
     <p>This is the about page!</p> 
    </div> 
</template> 

<script> 
    export default { 
    } 
</script> 

<style scoped> 

</style> 
+1

请尽量为创建webpackbin:

const app = new Vue({ router, template: '<App />', components: { App } }).$mount('#app') 

可优选被替换。这真的很奇怪,它不工作,所以你可能在代码的某处有一些小错误... –

+0

对不起@MU,我刚刚意识到我的代码有错误(最近有很多尝试错误,所以现在我不确定如何工作^^'),但我发布的代码是错误的。我现在已经更新了它(更改了main.js文件),请你再看一遍吗? –

+0

另外,当我检查Chrome中的页面时,我看到'

',所以我的'App'组件根本没有被渲染。 –

回答

4

我终于搞定了。 main.js文件应该这样写:

import Vue from 'vue' 
import VueRouter from 'vue-router' 
import App from './App' 
import Home from './pages/Home' 
import About from './pages/About' 

Vue.use(VueRouter) 

const routes = [ 
    { path: '/', component: Home }, 
    { path: '/about', component: About } 
] 

const router = new VueRouter({ 
    routes 
}) 

const app = new Vue({ 
    router, 
    template: '<App />', 
    components: { 
     App 
    } 
}).$mount('#app') 

我希望这可以为别人节省数小时的麻烦。

编辑

以下:

const app = new Vue({ 
    router, 
    render: function(createElement){ 
     return createElement(App) 
    } 
}).$mount('#app') 
+0

关于编辑,不同之处在于'template'选项是针对Vue的独立版本的,而如果使用纯运行时版本则需要'render'选项。 –