loading...

Multiple ways to set non-reactive values on a Vue component

scottstern06 profile image Scott ・1 min read

The Skinny

If you need non-reactive attributes on a Vue component, you can either use $options OR assigning an attribute to the Vue instance.

$options

export default {
  myConstant: 'hello',
  computed: {
    usingMyConstant() {
      return this.$options.myConstant
    },
  },
};

this.myConstant

export default {
  mounted() {
    this.myConstant = 'hello';
  },
  computed: {
    usingMyConstant() {
      return this.myConstant;
    },
  },
};

I recently came across a use case where we needed to set a non-reactive value in Vue. We could have either used $options or setting the property on the instance.

$options

I personally like using $options because when a developer is reading the declaration or the usage of values set in $options, it is SUPER explicit.

this.myConstant

If we need access to a value when the component is being mounted or created, we can just put a new property on the instance.

export default {
  mounted() {
    this.myConstant = asyncAvailableValue();
  },
};

When reading the code in the component, we might think that were missing a data property (myConstant), because we have set a new property on the instance. If you do choose this approach, you might want to make a comment explaining that this property should not be reactive in order to prevent other developers adding it to the data function.

// This should not be a reactive property, do not put on data attr.
this.myConstant = asyncAvailableValue();

Thanks for reading

Scott

Posted on by:

scottstern06 profile

Scott

@scottstern06

Frontend Engineer / You have problem, I contribute upstream(JS && OSS)

Discussion

pic
Editor guide