D
D
Dmi3ii2019-02-12 15:01:44
JavaScript
Dmi3ii, 2019-02-12 15:01:44

How to disable reactivity in a component?

There is a component (edit form) an object (array) flies into it. When creating, I want to save the object and track field changes (computed isChanged). When item.department changes, item_loaded.department also changes. Tell me how to disable reactivity? It didn't work through $options. There is an idea to try through Vuex, but it seems there is an easier way...

<template>
  <div>
    <h3 class="headline">Редактор</h3>
    <code>({{item_loaded.department}}={{item.department}})</code> //реактивно. всегда равно
    <h3 v-show="isChanged">(изменение)</h3>

    <v-autocomplete
        :items    = "app.departments"
        v-model = "item.department"
        label   = "Отдел"
    />

    <v-btn @click="save()" color="info">
        <v-icon left>fa-save</v-icon>Сохранить
    </v-btn>
  </div>
</template>

<script>
export default {
  props: {
      item: {
          type    : Object,
          default : null
      },
  },

  data() {
    return {
        item_loaded : null
    }
  },

  created() {
    this.item_loaded = this.item
  },

  computed: {
    isChanged() {
      if (this.item_loaded.department == this.item.department) {
        return false
      } else {
        return true
      }
    }
  },
}
</script>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-02-12
@Dmi3ii

When item.department changes, item_loaded.department also changes

this.item_loaded = this.item

Reactivity, yes. You don’t know the language, but you climb to use frameworks. It will be correct like this (google what is the difference between primitive data types and objects):
this.item_loaded = { ...this.item }
It is not very clear why created - in data, the context is a component instance, parameters are available, so you can copy an object right there:
data() {
  return {
    item_loaded: { ...this.item },
  };
},

Computed property isChanged - you can do it in one line instead of five:
isChanged() {
  return this.item_loaded.department !== this.item.department;
},

Why is null used as the default value for item? - you are accessing its properties, if you don't pass anything, you will get an error cannot read property of null. There must be an object:
default: () => ({ /* можно указать какие-нибудь свойства с дефолтными значениями */ }),

Mutate the parameter ( v-model="item.department"). It will be correct to emit changes to the parent component and update the object already there. In the parent, you chain the value for the item parameter with the sync modifier , and in the component in question, v-modelreplace it with setting the value and handling the input event:
<input
  :value="item.department"
  @input="$emit('update:item', { ...item, department: $event.target.value })"
>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question