1

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),
      };
    },

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.