DEV Community

Scott
Scott

Posted on

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

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
    },
  },
};
Enter fullscreen mode Exit fullscreen mode

this.myConstant

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

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();
  },
};
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

Thanks for reading

Scott

Top comments (1)

Collapse
 
lcichanowicz profile image
Lee C. • Edited

This is not working for me. I am trying to make an immutable/const from a value that originates in my data function. It returns null. If I omit the "$options", I get my value, but it is reactive.