For my first attempt at building a SPA with Vue, I decided to re-use a few functions but encountered some issues. The error message
"this.ExperienceToLevel is not a function"
kept popping up and it left me puzzled.
Furthermore, I'm contemplating if creating a plugin is truly the optimal approach for what I'm trying to accomplish. My goal is to make certain functions global "the Vue way". However, I am adamant about not resorting to assigning them to window using
window.UserLevel = new UserLevel()
.
The content of UserLevel.js:
/*
Create Levels array
*/
let Levels = [];
for (let i = 0; i < 100; i++) {
let xp = Math.floor(Math.pow(i, 1.3) * 100);
Levels.push(xp);
}
/*
Create UserLevel Plugin
*/
const UserLevel = {
install(Vue, options) {
Vue.ExperienceToLevel = function (xp) {
for (const [level, levelXP] of Object.entries(options.levels)) {
if (levelXP > xp) {
return level-1;
}
}
}
Vue.LevelToExperience = function (level) {
return options.levels[level];
}
Vue.ExperiencePercent = function (level) {
return ((this.xp - this.LevelToExperience(this.level)) / (this.LevelToExperience(this.level + 1) - this.LevelToExperience(this.level))) * 100;
}
}
};
export {
Levels,
UserLevel
};
Attempted to import the plugin into a component as follows:
import { UserLevel, Levels } from './../../UserLevel';
Vue.use(UserLevel, { levels: Levels });
Then utilized the global methods like this: this.ExperienceToLevel(this.xp)