I'd like to know how i can access my component messages (this.messages) from inside the chat socket on message function, so I can push a new message to my messages
Defining the websocket as a property is the way I managed to make it work. If there is a better way of doing it, I will be open to understand.
<script>
import axios from 'axios'
export default{
data () {
return {
messages: [],
conversation_id: 'global',
content: '',
tweeker: this.$store.state.username,
formatted_time: 'Now',
avatar: '',
chatSocket: null,
}
},
created() {
var loc = window.location, new_uri;
if (loc.protocol === "https:") {
new_uri = "wss:";
} else {
new_uri = "ws:";
}
new_uri += "//" + "127.0.0.1:8000";
this.chatSocket = new WebSocket(
new_uri +
'/ws/' +
'chat/' +
'0' +
'/'
);
this.chatSocket.onmessage = function (e) {
const data = JSON.parse(e.data);
// append message to messages
this.messages.push(data);
setTimeout(() => {
window.scrollTo(0, document.body.scrollHeight);
}, 0);
};
this.getMessages();
},
methods: {
async getMessages(){
await axios.get(`/api/messages/global`,)
.then(response => {
for (let i = 0; i < response.data.messages.length; i++) {
this.messages.push(response.data.messages[i])
}
this.scrollToBottom();
}).catch(error => {
console.log('error' + error)
})
},
submitMessage() {
if (this.content.length > 0) {
let message = {
'content': this.content,
'tweeker_name': this.$store.state.username,
'formatted_time': this.formatted_time,
'avatar_url': this.avatar,
'conversation_id': '',
};
this.chatSocket.send(JSON.stringify(message));
this.content = '';
}
},
scrollToBottom() {
window.scrollTo(0, document.body.scrollHeight);
}
}
}
</script>