I have been working on developing a Vue plugin. The plugin includes a custom method called customMethod
for each component, which I want to execute after the page has been mounted/created. Although everything seems to be working fine in a basic way, I am facing an issue with accessing this
inside the customMethod.
When I try to console.log(this)
, it simply logs 'undefined'.
So, my question is: How can I properly access this
inside my customMethod
?
var defaultParms = Object.freeze({
start : function(){},
leave : function(){}
});
const myPlugin = {
install(Vue, options = []) {
var ref = Vue.util;
var extend = ref.extend;
var assets = Object.create(null);
extend(assets, defaultParms);
Vue.options.customMethod = assets;
// set option merge strategy
var strats = Vue.config.optionMergeStrategies;
if (strats) {
strats.customMethod = (parent, child, vm)=>{
if (!child) return parent;
if (!parent) return child;
var ret = Object.create(null);
extend(ret, parent);
for (var key in child) {
ret[key] = child[key];
}
return ret
};
}
Vue.mixin({
customMethod:{
start: function(){
console.log('hi') // log 'hi'
console.log(this.$appName) // log 'undefined'
}
},
created: function () {
if(this.$options.customMethod){
this.$options.customMethod.start && this.$options.customMethod.start();
}
}
});
Vue.prototype.$appName = 'vikash';
}
}
Vue.use(myPlugin)
new Vue().$mount('#app')
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>