点击和网址更改后如何更新组件?

时间:2017-10-14 16:00:29

标签: javascript vuejs2 vue-router

我尝试使用vue-router,但出了点问题。

在页面上呈现路由器链接,通过单击URL更改。 localhost /#/ - > localhost /#/ contacts但组件窃取主页。仅在页面重新加载时更新。

main.js

import Vue from 'vue';
import VueRouter from 'vue-router';
import App from './index.vue';
import Error404 from './404.vue';
import Routes from './route';


Vue.use(VueRouter);
const router = new VueRouter({
    mode: 'hash',
    routes: Routes
});

window.onload = () => {
    new Vue({
        router: router,
        el: '#app-container',
        data: {
            currentRoute: window.location.hash.split('#')[1]
        },
        computed: {
            ViewComponent () {
                return Routes.filter(item => item.path == this.currentRoute)[0] || Error404
            }
        },
        render (h) { return h(this.ViewComponent.component ? this.ViewComponent.component : this.ViewComponent) }
    });
}

route.js

const routes = [
    {path: '/', component: mainPage},
    {path: '/example1', component: examplePage},
    {path: '/example2', component: exampleForm},
    {path: '/contacts', component: contacts}
];

export default routes

index.vue

<template lang="jade">
    div(id="app")
        router-link(to="/example1") Example1
        br
        router-link(to="/example2") Example2
        br
        router-link(to="/contacts") Contacts
</template>
<script type="text/javascript">
    export default {

    }
</script>

2 个答案:

答案 0 :(得分:0)

我通过添加

修复问题
watch: {
            '$route'(to, from) {
                this.$router.go(this.$router.currentRoute)
            }
        }

对于main.js,但我认为这是非常糟糕的解决方案。

答案 1 :(得分:0)

你遗失了router-view。路由器需要显示的this is the component responsible to render the component

请考虑基于official boilerplate的代码结构:

<强> main.js

import Vue from 'vue'
import App from './App'
import router from './router'

new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App }
})

<强> index.vue

<template>
  <div id="app">
    <router-view/>
    <router-link to="example1">example1</router-link>
    <router-link to="example2">example2</router-link>

  </div>
</template>

index.js(与您的route.js一样)

import Vue from 'vue'
import Router from 'vue-router'
import example1 from '@/components/example.vue'
import example2 from '@/components/example2.vue'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/example-1',
      name: 'example-1',
      component: example1
    }
    {
      path: '/example-2',
      name: 'example-2',
      component: example2
    }
  ]
})