1

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

<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 行为?

4

1 回答 1

0

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 中。

于 2021-08-06T04:51:11.987 回答