【问题标题】:Vue - Keep default Router-View alive when change another named viewVue - 更改另一个命名视图时保持默认路由器视图活动
【发布时间】:2020-04-06 14:48:40
【问题描述】:

情况:

除了默认路由视图之外,我还使用了一个命名路由视图。我想在调用 ArticleComponent 时保持 DEFAULT 路由视图处于活动状态,但是如您所见,您可以从 2 个不同的路由/组件调用 ArticleComponent。可以在代码 sn-p 下找到小提琴链接。

我想做的事:

如果我从 ListingComponent 打开 ArticleComponent,那么 ListingComponent 应该在默认路由视图中保持活动状态。

如果我从 FeedComponent 调用 ArticleComponent,那么 FeedComponent 应该在默认路由视图中保持活动状态。

我的代码:

const HomeComponent = {
    template: '<h4>Home</h4>'
};

const FeedComponent = {
    template: `<div>
    <h4>FeedComponent</h4>
    <router-link to="/article/1">Article 1</router-link> -
    <router-link to="/article/2">Article 2</router-link>
  </div>`
};

const ListingComponent = {
    template: `<div>
    <h4>ListingComponent</h4>
    <router-link to="/article/1">Article 1</router-link> -
    <router-link to="/article/2">Article 2</router-link> -
    <router-link to="/article/3">Article 3</router-link>
  </div>`
};

const ArticleComponent = {
    template: `<h4>Article {{ $route.params.id }}</h4>`
};

const routes = [
    {
    path: '/',
    component: HomeComponent
  },
  {
    path: '/feed',
    component: FeedComponent
  },
  {
    path: '/listing',
    component: ListingComponent
  },
  {
    path: '/article/:id?',
    components: { 
      default: FeedComponent, // <--- dynamically
      secondary: ArticleComponent
    }
  }
];

const router = new VueRouter({
    routes
});

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

小提琴:

https://jsfiddle.net/kvnvooo/b589uvLt/9/

【问题讨论】:

    标签: vue.js vuejs2 vue-router


    【解决方案1】:

    您可以使用Navigation guards 动态更改默认组件...

    {
        path: '/article/:id?',
        components: {
          default: FeedComponent,
          secondary: ArticleComponent
        },
        beforeEnter: (to, from, next) => {
            if(from.fullPath === '/listing') {
            to.matched[0].components.default = ListingComponent
          } else if(from.fullPath === '/feed') {
            to.matched[0].components.default = FeedComponent
          }
          next();
        }
      }
    

    https://jsfiddle.net/dhmLby6f/7/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-09
      • 2016-07-16
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 2017-08-24
      • 2018-05-19
      • 2021-04-13
      相关资源
      最近更新 更多