loading...
Cover image for Share functions between Vue and Node

Share functions between Vue and Node

octaneinteractive profile image Wayne Smallman ・2 min read

Vue and Node make a powerful and versatile team, but aside from the API — via Express for me — Vue doesn't talk to Node, or vice versa, and I had to fix that.

So there I was, building the front end, writing the code for a utilities mixin to store functions to handle common string and number operations. But then I realized that I had also written much the same code in a controller for Node.

What if I could use the same functions in Node and Vue?

So, first I created a file in Node that would contain the core functions I'd be using in the mixin in Vue:

// "utilities.js" in Node.

let utilities = {}

utilities.stripTags = (note, hellip = false) => {
  let removeHTML = note.replace(/(<([^>]+)>)/ig, "")
  let removeHTMLEntities = removeHTML.replace(/&#{0,1}[a-z0-9]+;/ig, "")
  let removeLineBreaks = removeHTMLEntities.replace(/\r?\n|\r/g, " ")
  let removeNonbreakingSpaces = removeLineBreaks.replace(/&nbsp;/ig, " ")
  let removeEmojies = removeNonbreakingSpaces.replace(/[\u1000-\uFFFF]+/g, " ")
  let string = removeEmojies
  return (hellip) ? string.concat('&hellip;') : string
}

module.exports = utilities

… then, I returned to the mixin:

// "utilities.js" in Vue.

'use strict'

// Core modules.
import CoreUtilities from 'path_to/utilities'

export const Utilities = {
  data () {
    return {
      // Reactive variables...
    }
  },
  methods: {
    stripTags (note, hellip = false) {
      // Utilizing a method in core utilities.
      return CoreUtilities.stripTags(note, hellip)
    }
  }
}

Now I have one definitive source of functions that both Vue and Node are able to access.

If anyone knows a more efficient method of replacing HTML, please share!

Image by Dyanap from Pixabay

Discussion

pic
Editor guide