【问题标题】:Is there an equivalent in Angular to Vue.js keep-alive and component?Angular 中是否有与 Vue.js keep-alive 和组件等价的东西?
【发布时间】:2021-10-11 00:15:45
【问题描述】:

我正在学习 Vue.js,我尝试了 keep-alivecomponent 机制,它允许在组件之间动态切换。据我了解,我可以这样做:

<template>
  <section>
    <button @click="setSelectedTab('section-a')">Section A</button>
    <button @click="setSelectedTab('section-b')">Section B</button>
  </section>

  <keep-alive>
    <component :is="selectedTab"></component>
  </keep-alive>
</template>

export default defineComponent({
  name: "SomeComponent",
  components: {
    SectionA,
    SectionB,
  },
  data() {
    return {
      selectedTab: 'section-a',
    };
  },
  methods: {
    setSelectedTab(tab: string): void {
      this.selectedTab = tab;
    },
  },
});
</script>

上面的代码将根据点击哪个按钮显示SectionASectionB组件,同时确保未显示的组件保持活动状态,保持其内部状态。

在 Angular 中,我必须执行以下操作:

import { Component } from '@angular/core';

@Component({
  selector: 'app-some',
  template: `
    <section>
      <button (click)="setSelectedTab('section-a')">Section A</button>
      <button (click)="setSelectedTab('section-b')">Section B</button>
    </section>
    
    <app-section-a *ngIf="selectedTab === 'section-a'"></app-section-a>
    <app-section-b *ngIf="selectedTab === 'section-b'"></app-section-b>
  `,
  styleUrls: ['./resources.component.scss']
})
export class SomeComponent {
  selectedTab = 'section-a';
  
  setSelectedTab(tab: string): void {
    this.selectedTab = tab;
  }
}

我想如果我想保持组件的内部状态,我应该使用以下内容:

<app-section-a [ngStyle]="{ display: selectedTab !== 'section-a' ? 'none' : 'block' }"></app-section-a>
<app-section-b [ngStyle]="{ display: selectedTab !== 'section-b' ? 'none' : 'block' }"></app-section-b>

有没有更好的方法在 Angular 中实现 Vue.js 的行为?

【问题讨论】:

  • 在角度你应该使用一个行为主题,它将使用 rxjs 为你的组件数据保持状态 - 它有点不稳定,但它运作良好。

标签: angular vuejs3 angular-dynamic-components vue-dynamic-components


【解决方案1】:

Keep Alive,当包裹在动态组件上时,缓存不活动的组件实例而不破坏它们。重要的一点是,当此类组件被切换时,Vue 调用生命周期事件激活和停用(替代安装和卸载)。

在 Angular 中,无法缓存模板内的组件。但是,有一种方法可以缓存基于路由器的组件。见https://medium.com/swlh/how-to-toggle-caching-for-routing-components-in-angular-5a327ea87310。但是,这不适合您的需要。

来到您的用例,这取决于,如果需要在选项卡切换之间调用生命周期方法(OnInit,OnChanges 等)*ngIf 方法将是首选,因为它删除了DOM 树中的组件,并在需要显示时再次构造它。

更改display 只会导致组件不可见,但 DOM 树的组件仍将存在于 DOM 中。

【讨论】:

    猜你喜欢
    • 2022-01-10
    • 2018-05-26
    • 2014-10-14
    • 2012-12-30
    • 2020-07-21
    • 1970-01-01
    • 2021-09-17
    • 2018-06-01
    • 2018-01-07
    相关资源
    最近更新 更多