socket.io-client redefines this
inside function, can't call any other function or variable
#3920
-
I am working on a vue.js application when I found out that <script>
import io from "socket.io-client";
var socket = io.connect("http://localhost:5000");
export default {
name: "Home",
data() {
return {
messages: ['Foo', 'Bar'],
message: ""
};
},
methods: {
send: function() {
socket.send(this.message);
this.message = "";
}
},
mounted() {
socket.on("connect", function () {
socket.send("User has connected!");
});
socket.on("message", function (msg) {
this.messages.push(msg); // This line
console.log("Received message");
});
},
};
</script> This gives me an error
Then I found out that the this variable is redefined by this function that. Anyone can help me, So that I can append the message to the list in vue.js. |
Beta Was this translation helpful? Give feedback.
Answered by
darrachequesne
May 15, 2021
Replies: 1 comment 1 reply
-
Did you try with an arrow function: socket.on("message", (msg) => {
this.messages.push(msg); // This line
console.log("Received message");
}); If I'm not mistaken, in your code example above, the |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
krodh
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Did you try with an arrow function:
If I'm not mistaken, in your code example above, the
this
points towards thesocket
object, hence theCannot read property 'push' of undefined
.