Mossen
Mossen

Reputation: 604

Vuejs clone object in script tag or inside instance e.g. data

Wondering what is the best practice for such code here and what is the difference when cloning an object inside script tag or doing it in data property:

<script>
  import {cloneDeep} from "lodash";
  import {INVITE_USER_FORM_FIELDS} from './data';

  const FORM_FIELDS = cloneDeep(INVITE_USER_FORM_FIELDS);

  export default {
    name: "ModalInviteCreate",
    data() {
      return {
        FORM_FIELDS,
      };
    },

OR

<script>
  import {cloneDeep} from "lodash";
  import {INVITE_USER_FORM_FIELDS} from './data';

  export default {
    name: "ModalInviteCreate",
    data() {
      return {
        FORM_FIELDS: cloneDeep(INVITE_USER_FORM_FIELDS),
      };
    },

Upvotes: 1

Views: 45

Answers (1)

AlexMA
AlexMA

Reputation: 10202

The difference is the data method will run every time you create a new instance of that component. If you never need to recompute a deep clone, then option 1 is preferable since the extra clones are a waste. If you're bothering to create a deep clone though, I'm guessing it's so your components can safely mutate the object without modifying the original. So option 2 is probably the best choice, otherwise all of the component instances would all share the same object.

Here's an example to illustrate, see the console.logs.

const fakeDeepClone = name => { 
  console.log(`creating data for component ${name}`);
  return { name };
}

const aData = fakeDeepClone('a');

const componentA = {
  template: '<div>name: {{name}}</div>',
  data() {
    return aData
  }
}

const componentB = {
  template: '<div>name: {{name}}</div>',
  data() {
    return fakeDeepClone('b')
  }
}

var app = new Vue({
  el: '#app',
  components: {
    componentA,
    componentB
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <component-a></component-a>
  <component-a></component-a>
  <component-b></component-b>
  <component-b></component-b>
</div>

Upvotes: 2

Related Questions