Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cklmercer's avatar

VueJS plugin: FeathersJS services

Lately, I've found myself making lots of little plugins likes these for my VueJS applications.

This one extends Vue.prototype and vm.$options.

Thanks!

Plugin

// Execution starts here.
function plugin(Vue, feathers)  {
    // Only install the plugin once.
    if (plugin.installed) {
        return
    }

    // Bind access to underlying FeathersJS client into all vm.
    Object.defineProperty(Vue.prototype, '$api', {
        get() {
            return feathers
        }
    })

    // Register a global VueJS mixin.
    Vue.mixin({ 
        // Hook into the first VueJS 2.0 life-cycle event.
        beforeCreate() {
            registerServices(this)
        },
        // Hook into the first VueJS 1.0 life-cycle event.
        init() {
            registerServices(this)
        }
    })
}

// Bind the services in the given components "services" option.
function registerServices(vm) {
    
    let services = vm.$options.services

    // Exit if there isn't a valid "services" option.
    if (typeof services !== 'object') {
        return
    }
    
    // Get an instance of the vm's "data" option.
    let data = typeof vm.$options.data === 'function' ? vm.$options.data() : vm.$options.data

    // Create a default data instance if necessary.
    if (typeof data === 'undefined') {
        data = {}
    }

    // Bind each FeathersJS service into our vm data instance.
    for (var service in services) {
        data[service] = vm.$api.service(services[service])
    }

    // Update the vm's "data" option for other life-cycle events.
    vm.$options.data = function () { return data }
}

export default plugin

Psuedo-Code Example

import Vue from 'vue'
import plugin from './plugin'
import app from './app' // FeatherJS client instance.

// Install plugin.
Vue.use(plugin, app)

// Create a Vue component that will use a FeathersJS service.
Vue.component('example-usage', {
    name: 'example-usage',

    // bind app.service('users') to this.userService
    services: {
        userService: 'users'
    },

    created() {
        // Call the `users` service and log the results.
        this.userService.find({})
            .then(console.log)
            .catch(console.error)
     }
})
0 likes
0 replies

Please or to participate in this conversation.