在我的TaskList.vue中,我有以下代码:
<template>
<div>
<ul>
<li v-for="task in tasks" v-text="task"></li>
</ul>
<input type="text" v-model="newTask" @blur="addTask">
</div>
</template>
<script>
export default {
data(){
return{
tasks: [],
newTask: ''
}
},
created(){
axios.get('tasks')
.then(
response => (this.tasks = response.data)
);
Echo.channel('task').listen('TaskCreated', (data) => {
this.tasks.push(data.task.body);
});
},
methods:{
addTask(){
axios.post('tasks', { body: this.newTask })
this.tasks.push(this.newTask);
this.newTask = '';
}
}
}
</script>
当我点击axios.post(&#39; tasks&#39;)终点时,我在当前标签中得到了重复的结果,我输入了值,而另一个标签只有1个正确的值。
为避免这种情况,我尝试使用 广播(新的TaskCreated($ task)) - &gt; toOthers();
OR
我把$ this-&gt; dontBroadcastToCurrentUser()放在我的TaskCreated.php的构造中
但是,这两种方法都不起作用。知道为什么吗?
下面的图片来自我的网络标签。其中一个待定,是什么导致了这个问题?
https://ibb.co/jpnsnx(抱歉,由于需要更多声誉,我无法发布图片)
答案 0 :(得分:3)
我通过手动发送带有axios post的X-Socket-Id在我的Laravel Spark项目中解决了这个问题。
文档说如果您正在使用vue和axios,标题会自动添加,但对我来说(因为火花?)它不是。
下面是一个示例,说明如何使用Laravel Echo中的活动socketId手动将X-Socket-Id标头添加到axios帖子中:
axios({
method: 'post',
url: '/api/post/' + this.post.id + '/comment',
data: {
body: this.body
},
headers: {
"X-Socket-Id": Echo.socketId(),
}
})
答案 1 :(得分:0)
Laravel在使用$ this-> dontBroadcastToCurrentUser();时查找标题X-Socket-ID;通过该ID,Laravel可以确定要从事件中排除的用户(当前用户)。
您可以为请求添加拦截器,可以在其中将套接字实例的ID添加到每个请求的标头中:
/**
* Register an Axios HTTP interceptor to add the X-Socket-ID header.
*/
Axios.interceptors.request.use((config) => {
config.headers['X-Socket-ID'] = window.Echo.socketId() // Echo instance
// the function socketId () returns the id of the socket connection
return config
})