programing

Vue가 동적 구성 요소를 사용하여 Vuex에서 v-for의 항목을 업데이트하지 않음

sourcetip 2022. 8. 8. 23:02
반응형

Vue가 동적 구성 요소를 사용하여 Vuex에서 v-for의 항목을 업데이트하지 않음

동적인 컴포넌트가 있습니다.tabbody로 정의되어 있습니다.

<component :is="currentTab.itemType" :itemId="currentTab.itemId"></component>

템플릿에는 스팬이 있으며, 이는itemId- 이 값은 매번 변경됩니다.currentTab탭에서 호스트 구성 요소가 변경되었습니다.

의 각 컴포넌트tab.itemTypeVuex 모듈이 있으며 특정 유형에 속합니다.

예를 들어 스토어 모듈이 있습니다.product상태 설명:

{
  products: { [itemId: string]: IProduct }
}

컴포넌트가 생성된 경우 또는itemId변경된 경우 로드 액션을 실행하여 로드된 제품을productsvuex 상태의 경우

Vue 계산 속성이 있습니다.

@State(productNamespace)
state: IProductState;

get currentProduct() {

  return this.state.products[this.itemId];
}

또는 심지어

@Getter(GetterNames.GET_PRODUCT_BY_ID, bindingOptions)
getProductById: (itemId: string) => IProduct;

get currentProduct() {

  return this.getProductById(this.itemId);
}

각 제품에는attributes목록, 반복 기준v-for와 함께:key.

<v-list :key="itemId"><!-- itemId has no effect there -->
  <v-list-item v-for="attribute in currentProduct.attributes" :key="attribute.id">
    ...
  </v-list-item>
</v-list>

문제는 우리가 변화할 때itemId속성 목록에는 마지막으로 추가한 제품의 모든 속성이 표시되며 다른 제품으로 이전 "예"로 전환해도 새로 고침되지 않습니다.itemId하지만 똑같다itemType.

세팅하려고 했는데:key부모의div~하듯이itemId아무 효과도 없어요.설정했을 때:key로.<component>, vuex 상태가 깨집니다.

Vue 버전은 2.6.10입니다.

갱신:

제품의 단순한 특성으로도 작동하지 않습니다.

{{ currentProduct.name }}

요약:.

이 있습니다.itemId속성을 입력합니다.그리고 계산한 속성은 그것에 달려있다.따라서 계산된 속성은 다음과 같은 경우 변경을 반영하지 않습니다.itemIdVuex 컬렉션이 변경되지 않는 동안 프로포트가 변경되었습니다.

확인필:

계산된 속성은 state.products 컬렉션이 변경된 경우에만 갱신됩니다.나는 달리기를 통해 이것을 모방했다.createProduct각 탭 전환에 대한 작업입니다.vuex 상태의 수집이 패치되지 않은 제품 스터브를 수락하고 법적 변경 사항을 반영합니다.currentProduct주어진 것과 함께itemId

업데이트 2: 감시자가 있는 구성 요소.아직 아니야...

@Component
export default class Product extends Vue {

  @Prop({ type: Object, required: true })
  readonly tabItem: ITabItem;

  @State(productNamespace)
  state: IProductState;

  itemId: string;

  created() {

    //...
    this.initCurrentProduct();
  }

  // No changes until state.products was changed.   
  get currentProduct(): IProduct | {} {

    if (!this.state) return {};     
    return this.state.products[this.itemId];
  }

  @Watch('tabItem')
  onTabItemChanged()
  {
    DEBUG && console.log('Tab changed: keep moving!');
    this.initCurrentProduct();
  }

  private async initCurrentProduct() {

    const { isNew, itemId } = this.tabItem;

    if (itemId === this.itemId)
      return;

    DEBUG && console.log('ItemId changed.');
    this.itemId = itemId;

    // ...
  }

  // ...
}

그럼 동적 컴포넌트에 전달되는 속성은currentTab.itemId즉, itemId는 실제로는 IdemId에 있는currentTab루트 Vue 데이터 개체가 아닌 개체입니까?

Vue는 기본적으로 중첩된 개체를 추적하지 않으며 전체 개체가 변경될 때만 다시 그리기를 트리거합니다(예: 다음과 같은 작업을 수행하는 경우).currentTab = {...}). 다음 중 하나를 수행할 수 있습니다.

  1. 감시자를 사용하다currentTab와 함께deep: trueattribute : https://vuejs.org/v2/api/ #watch, 다음으로 redraw를 트리거합니다.this.$forceUpdate언제든지 불러주세요.

  2. 이동itemId데이터의 근원을 파악해, 거기서부터 갱신하는 것만으로,

당신의 vuex 돌연변이에

let items = [...state.items]; // create a new copy

// mutate it 
items.map(item => item.selected = true);

// return the new copy
state.items = items;

언급URL : https://stackoverflow.com/questions/57528676/vue-does-not-update-items-in-v-for-from-vuex-with-dynamic-component

반응형