vue.jsvuejs3

Remaking Vue.prototype.$dbCon in a Vue 3 project


I'm refactoring a Vue 2 project into Vue 3, and honestly have little idea what I'm doing. I've somehow got most of it working, but I can't find a good replacement for Vue.prototype that fits the scenario.

dbConnector.js

dbConnector.install =  function(Vue, options) {
  console.log("Installing dbConnector... ");

  Vue.prototype.$dbCon = {
    testConnection: function() {
       return "Testing connection: Connector listening...";
    },
    requestViewData: function(caller, param) {
        var url = "dataRequest.php";
        return dbConnector.createGETPromise(caller, url, param);
    },
    ...
  }

}

Home.vue (child of app.vue)

  async mounted () {

    console.log("Testing PHP connection")
    // this.$store.commit('logger/addEntry', {message: "Testing PHP connection"})
    this.$dbCon.requestViewData(...)
    ...
}

main.js (in Vue 3 if it helps)

import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
import router from './router'
import dbCon from './resource/dbConnector'

const app = createApp(App)
  .use(store)
  .use(dbCon)
  .use(router)
  .mixin(dbCon)
  .mount('#app');

My personal best idea is using provide/inject, but I haven't had much luck with it

new dbConnector.js

dbConnector.install = function (Vue, options) {
  console.log("Installing dbConnector... ");
  var dbCon = {
    requestViewData: function(caller, param) {
        var url = "dataRequest.php";
        return dbConnector.createGETPromise(caller, url, param);
    },
    ...
   }
   provide('$dbCon', dbCon)
}

new home.vue


    console.log("Testing PHP connection")
    console.log("dbCon: ", inject('$dbCon'));
    //Retuns dbCon: undefined
    $dbCon.requestViewData(...)
    //Throws Cannot read properties of undefined (reading 'requestViewData')

Solution

  • As Estus said, using provide/inject is overengineering for what I needed and I could've just made dbCon accessible from the export of dbConnection.vue