O
O
Oleg Trubin2020-10-14 17:46:32
Vue.js
Oleg Trubin, 2020-10-14 17:46:32

How to use object property as value for props (losing reactivity)?

Hello.
There are 2 components: a list and a list element.

See code below.
The problem is this:
As the value of one of the input parameters (isEdit), I try to use the value of the property of the object (editState)
But when I change the value of the property, the value of the corresponding props does not change.
Those. reactivity in this case does not work?
How would you implement what you have planned?

List:

<template>
  <div class="edit-tag-list">
    <h3>Список тегов</h3>
    <EditTagItem
      v-for="(tagName, key) in tagsAsArray" :key="key"
      :name="tagName"
      :isEdit="editState[tagName]"
      @startEditingTagName="startEditingTagName"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import EditTagItem from './EditTagItem.vue';

export default {
  name: 'EditTagList',
  components: { EditTagItem },
  data: () => ({
    editState: {},
  }),
  computed: {
    ...mapGetters('tags', ['tagsAsArray']),
  },
  methods: {
    startEditingTagName(tagName) {
    this.editState[tagName] = true;
    },
  },
  created() {
    this.tagsAsArray.forEach((item) => {
      this.editState[item] = false;
    });
  },
};
</script>


List element (redundant removed):
<template>
  <div class="edit-tag-item d-flex clearfix">
    <template v-if="isEdit">
        <input class="mr-auto"/>
        <b-icon class="edit-tag-icon edit-tag-icon-edit" icon="check2-square" variant="success"b-icon>
    </template>
    <template v-else>
        <span class="edit-tag-name mr-auto">{{ name }}</span>
        <b-icon class="edit-tag-icon edit-tag-icon-edit" icon="pencil-square" variant="primary" @onClick="editTagName"></b-icon>
    </template>
  </div>
</template>

<script>
export default {
  name: 'EditTagItem',
  components: {
    clickableWrapper,
  },
  props: {
    name: String,
    isEdit: Boolean,
  },
  methods: {
    editTagName() {
      this.$emit('startEditingTagName', this.name);
    },
  },
};
</script>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-10-14
@otrubin

created() {
  this.tagsAsArray.forEach((item) => {
    this.editState[item] = false;
  });
},

No, this way the editState properties will not be reactive .
Create a new object instead of modifying an existing one:
created() {
  this.editState = Object.fromEntries(this.tagsAsArray.map(n => [ n, false ]));
},

Another wildly suspicious thing is hooking up a click handler in a list item component:
@onClick="editTagName"

I can't remember if I've ever seen a vue component's event name prefixed with "on". Maybe it should just be "click"? Check just in case.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question