[英]How to make a realtime crud using vuex and socketio?
我想使用 vuex、node、express 和 socketio 執行實時 crud,但使用以下語法我無法得到結果。
服務器
index.js
const server = app.listen('3000',() => {
console.log('<--- Web Server Starter --->')
const io = require('./sockets')(server)
io.on('connection', socket=>{
console.log('client connected');
})
})
socket.js
let io
module.exports = {
init:httpServer =>{
io = require('socket.io')(httpServer)
return io
},
getIo:()=>{
if(!io){
throw new Error('socket io not initialized')
}
return io
}
}
用戶.js
const io = require('../socket')
router.post('/newuser',(req, res) => {
res.json({ serverResponse: 'userCreated' })
io.getIo().emit('newuser',{serverResponse:'created',user:user})
})
客戶
模塊 user.js(VUEX 動作)
getusers({ commit }){
const sessionToken = localStorage.getItem('sessionToken')
axios.get('/newuser', {
headers: {
Authorization: `Bearer ${localStorage.getItem('sessionToken')}`
},
})
.then(response => {
const socket = openSocket('http://localhost:3000')
socket.on('newuser', data => {
if (data.serverResponse === 'created') {
this.users = data.user
commit('GET_USERS', users)
})
})
.catch(error => {
alert(error)
})
})
當我創建新用戶時,用戶列表並沒有自動更新,但是我必須刷新頁面才能看到新用戶,為什么會出現這種情況?
這是因為在您的后端,您正在處理 post url-endpoint '/newuser'
以獲取數據。 您實際上並未使用 socketio 發布數據,因此如果您不更新頁面,您的axios.get
function 在您發布到的 ZDB974238714CA8DE634A7CE1DZF08 之前不會獲得任何新數據。 最好將您的套接字客戶端代碼放在 axios promise 之外,這樣數據主要由 socketio 在客戶端更新,而不是由 API 更新。
編輯:這是您客戶端中的代碼
getusers({
commit
}) {
const sessionToken = localStorage.getItem('sessionToken')
axios.get('/newuser', {
headers: {
Authorization: `Bearer ${localStorage.getItem('sessionToken')}`
},
})
.then(response => {
console.log('success');
})
.catch(error => {
alert(error)
})
const socket = openSocket('http://localhost:3000')
socket.on('newuser', data => {
if (data.serverResponse === 'created') {
this.users = data.user
commit('GET_USERS', users)
})
})
您對 promise 的 your.catch 部分有問題,因為它位於 .then 部分內,我還將您的套接字代碼移到了 promise 之外。
因此,當您發布到 /newuser 時,在您的服務器中。 您從客戶端上的 socketio 發送發射您不需要使用 axios 來檢查是否已觸發某些套接字事件,嘗試刪除 axios.get() 並保留
const socket = openSocket('http://localhost:3000')
socket.on('newuser', data => {
//do some thing
})
首先要明確一點,VUEX 是集中式的 state 管理,與“實時”無關。
您需要使用socket.io
和vue-socket.io
在服務器上設置事件監聽器
Socket.IO可以用Express實現,看這里
要在客戶端使用帶有 Socket.IO 的 VUEX, 請參閱此
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.