如何使用vue-router在加载页面时加载组件

时间:2020-08-18 10:44:55

标签: vue.js vue-router

只有当您单击“ /”时,我才能使用此代码,但我希望在我登陆页面时加载那些组件,而不必单击它。

const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
const Baz = { template: '<div>baz</div>' }

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '/',
      components: {
        default: Foo,
        a: Bar,
        b: Baz
      }
    },
    {
      path: '/other',
      components: {
        default: Baz,
        a: Bar,
        b: Foo
      }
    }
  ]
})
    
  

      new Vue({
            router,
          el: '#app'
        })

我的路由器文件

<div id="app">
  <h1>Named Views</h1>
  <ul>
    <li>
      <router-link to="/">/</router-link>
    </li>
    <li>
      <router-link to="/other">/other</router-link>
    </li>
  </ul>
  <router-view class="view one"></router-view>
  <router-view class="view two" name="a"></router-view>
  <router-view class="view three" name="b"></router-view>
</div>

我希望加载Foo和Bar and Baz,而无需单击它

这是一个jsfiddle

1 个答案:

答案 0 :(得分:1)

/other路由推入已安装的挂钩内的路由器中:

new Vue({
    router,
  el: '#app',
  
  mounted(){
  this.$router.push('/other')
  }
})