How to Make a Variable Created Outside of Vue Reactive

If you get a variable from outside of Vue, it's nice to be able to make it reactive if you need to.

That way you can use it in computed props, watchers, and everywhere else, and it works just like any other state in Vue.

If you're using the options API, all you need is to put it in the data section of your component:

const externalVariable = getValue();
export default {
data() {
return {
reactiveVariable: externalVariable,
};
}
};

If you're using the composition API with Vue 3, you can use ref or reactive directly:

import { ref } from 'vue';
// Can be done entirely outside of a Vue component
const externalVariable = getValue();
const reactiveVariable = ref(externalVariable);
// Access using .value
console.log(reactiveVariable.value);

Using reactive instead:

import { reactive } from 'vue';
// Can be done entirely outside of a Vue component
const externalVariable = getValue();
// Reactive only works with objects and arrays
const anotherReactiveVariable = reactive(externalVariable);
// Access directly
console.log(anotherReactiveVariable);

If you're still on Vue 2 (as many of us are) you can use observable instead of reactive to achieve exactly the same result.