Vue module component detect Vue.js version?

Viewed 167

I have a component I'd like to release to NPM with simple v-model functionality.

as such, it'd be ideal if it could run on vuejs 2/3 interchangeably.

I can brute force the behaviour for both by setting the component to emit input and update:modelValue but a more elegant solution would be to verify the user's implementation and emit accordingly. Is there a "version" property available somewhere in the toolchain at runtime? Alternatively, what would be the (or one of the) best way(s) to gracefully detect the version of the client's build?

2 Answers

Vue 3:

import * as Vue from 'vue';

console.log(Vue.version) // "3.0.0"

Vue 2:

import Vue from 'vue';

console.log(Vue.version) // "2.6.12"

To make a valid determination between the two, you can do this:

import * as Vue from 'vue';

// Make copy to prevent import warning in Vue 2
const vueObject = { ...Vue };
let version;

if (vueObject.default) version = 2;
if (vueObject.version && vueObject.version[0] === '3') {
    version = 3;
}
Related