简体   繁体   中英

Props not being saved to a local state in vue components

( follow-up ).

In

https://codesandbox.io/s/sjm0x

props are intended to be saved to a local object (for later use) and rendered from there. It should look/behave like:

https://codesandbox.io/s/v9pp6

("Books" and "Movies" are both draggable).

First working case:

<template>
  <div class="inventory-section-component">
    <draggable v-model="itemSectionProps.itemSectionCategory">
      <transition-group>
        <div
          v-for="category in itemSectionProps.itemSectionCategory"
          :key="category.itemSectionCategoryId"
        >
          <!-- <p>{{ category.itemSectionCategoryName }}</p>  -->
          <inventory-section-group-component :itemSectionGroupData="category">
          </inventory-section-group-component>
        </div>
      </transition-group>
    </draggable>
  </div>
</template>

produces:

在此处输入图像描述

but uses props directly and does not take into account mutations:

在此处输入图像描述

The second example:

<template> 
  <div class="inventory-section-component">
    <draggable v-model="this.itemSectionData.itemSectionCategory">
      <transition-group>
        <div
          v-for="category in this.itemSectionData.itemSectionCategory"
          :key="category.itemSectionCategoryId"
        >
          <inventory-section-group-component :itemSectionGroupProps="category">
          </inventory-section-group-component>
        </div>
      </transition-group>
    </draggable>
  </div>
</template>

saves props to a local object itemSectionData but the output no longer gets rendered:

在此处输入图像描述

First define itemSectionData as an empty object in your data method.

    data() {
      return {
        itemSectionData: {}
    };
  }

Then define a watcher for the prop itemSectionProps being passed to the component and assign it's values to the newly defined variable itemSectionData like such:

    watch: {
    itemSectionProps: {
      handler() {
        this.itemSectionData = this.itemSectionProps;
      }
    }
  }

You can then use the new variable within the component

Check this out https://codesandbox.io/s/dreamy-sun-smexc?file=/src/components/InventorySectionC.vue:1117-1242

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM