Estoy tratando de usar fetchEventSource (de @microsoft/fetch-event-source ) para procesar eventos enviados por el servidor para transmitir datos al cliente. Funciona, ya que se devuelven los datos y puedo registrarlos en la consola, pero cuando intento actualizar mis datos de vue en el evento onmessage , aparece el error:
TypeError: Cannot set properties of undefined (setting 'messages')
¿Alguna idea sobre la mejor manera de hacer que esto funcione?
Plantilla de prueba básica:
<template> <div> <p> <label>Message</label><br /> <textarea id="messages" v-model="messages"></textarea><br /> <button @click="getMessage">GET</button> </p> </div> </template>y el guión:
import { fetchEventSource } from "@microsoft/fetch-event-source"; export default { data() { return { messages: "", }; }, mounted() { this.messages = "initialized"; // this works }, methods: { getMessage() { fetchEventSource("url-here", { method: "POST", headers: { "Content-Type": "application/json", }, onmessage(msg) { console.log("message", msg.data); // this works - data is here! this.messages = msg.data; // this returns the error }, }); }, }, };Puedes probar con la función de flecha o como:
getMessage() { const self = this fetchEventSource("url-here", { method: "POST", headers: { "Content-Type": "application/json", }, onmessage(msg) { console.log("message", msg.data); // this works - data is here! self.messages = msg.data; // this returns the error }, }); },