I am using NuxtJS framework to build a Vue application. I writing a custom plugin for TinyMCE editor to upload images to server. This plugin is an ES6 module with a single export(I have taken out code for brevity). So here, image is selected -> compressed -> upload to server.
import { actions } from '@/store/common/post_editor.js'
const imageUpload = function (editor) {
function _onAction() {
let imageBlob = null
onChange: function (api, details) {
//get the image selected
compressImage(image).then((output) => {
imageBlob = output
})
}
},
onSubmit: function (api) {
actions
.uploadToServer(imageBlob)
.then((url) => {
editor.insertContent('<p><img src="' + url + '"/></p>')
})
.catch((error) => {
})
},
})
}
}
export { imageUpload }
I am importing Vuex action in the module that uploads the image to server. And following is the code for it.
uploadToServer(vuexContext, blob) {
return new Promise((resolve, reject) => {
let formData = new FormData()
formData.append('file', blob)
console.log(this.$axios) // this is undefined
this.$axios
.$post('/server/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
.then((res) => {
resolve(res.location)
})
.catch((error) => {
reject(error)
})
})
}
But when using this plugin, axios is not triggered. And apparently the reason is this.$axios is undefined. So, it seems this is not the correct way to import Vuex action into an ES6 module.
Any help is appreciated, thanks.
EDIT
For now, I am using
window.$nuxt.context.store .dispatch('common/post_editor/uploadToServer', imageBlob)
But not sure if this is a good practice.
Vue and Nuxt plugins define properties on component instances. this inside an action is not component instance and so isn't supposed to have this.$axios. It's an outdated and questionable practice to use loosely defined this dynamic context anywhere besides strict OOP code.
It's incorrect way yo use an action. A store should be imported instead of an action:
import store from '.../store`.
It's incorrect way to import Axios. It should be explicitly imported in non-component modules. In case there's Axios instance with interceptors, etc, it can be maintained within a module:
import axios from '.../common/axios`.