Search code examples
javascriptvue.jsvuejs2vue-componentosc

How to set a Vue variable equal to a function argument?


I am making a web app that can send and receive OSC data via a node.js server. That's all working fine. But I want to use Vue.js for the front and here I get a problem with declaring a function. When I am using only JavaScript it's working well.

Javascript:

import osc from "osc";
var port = new osc.WebSocketPort({
  url: "ws://localhost:8083" //localhost:8083 online server 178.62.209.37:8083
});
port.open();

var message = []

OSCMessage();

function OSCMessage() {
  port.on("message", function(oscMessage) {
    //console.log(oscMessage);
    OSCMessages(oscMessage);
  });
}

function OSCMessages(oscMessage) {
  message = oscMessage;
  console.log(message);
}

But when I try to put it into Vue, I get an error in the console, even when I try it with this.OSCMessages:

OSCMessages is not defined

Vue code:

import osc from "osc";
var port = new osc.WebSocketPort({
  url: "ws://localhost:8083" //localhost:8083 online server 178.62.209.37:8083
});
port.open();

export default {
  data() {
    return {
      value: 60,
      message: [],
    }
  },
  computed: {
    OSCMessage: function() {
      port.on("message", function(oscMessage) {
        //console.log(oscMessage); // this console log is working great.
        this.OSCMessages(oscMessage)
      });
    },
    OSCMessages: function(oscMessage) {
      this.message = oscMessage
      console.log(this.message.address);
    },
  },
}

My goal is to make the Vue variable message equal to the oscMessage, so that I can continue to use the oscMessage data in Vue. I think it has something to do with scoping in Vue. I hope someone can help me, thanks in advance!


Solution

  • There are two issues.

    1) If you don't use an es6 arrow function as a callback, then this will not refer to the Vue instance.

    Change this:

    port.on("message", function (oscMessage) {    
       this.OSCMessages(oscMessage)
    });
    

    to:

    port.on("message", (oscMessage) => {    
       this.OSCMessages(oscMessage)
    });
    

    2) These both appear to be methods, not computeds. Or at least OSCMessages is being called like a method. You can't pass arguments to computeds.

    Change:

    computed: {
    

    to

    methods: {