Vue.js + socket.io 如何更新道具

Vue.js + socket.io how to update props

所以这是我的 Vue 用户列表组件。 Socket.io returns 当前活跃用户的列表,例如 [{name:Fluxed,rank:Admin}] 我希望它自动更新元素。如何更新 prop 元素然后使其显示更改?

这是我的代码

<template>
  <div id="app">
    <div>
    <div style="float:right;width:30%;border-left:1px solid black;padding:1%;">
      <b>Users</b>
      <b-list-group style="max-width: 300px;" >
        <b-list-group-item class="align-items-center" v-for="value in userList2" v-bind:key="value.name" >
          <b-avatar class="mr-3"></b-avatar>
          <span class="mr-auto">{{ value.name }}</span>
          <b-badge>{{ value.rank }}</b-badge>
        </b-list-group-item>
      </b-list-group>
      <ul class="list-group">
      </ul>
    </div>
  </div>
  </div>
</template>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

<script>
import io from 'socket.io-client';
import $ from 'jquery'
var socket = io('http://localhost:4000');
socket.on('update', function (users){
      this.userList = users;
      console.log(this.userList)
}) 
import VueJwtDecode from "vue-jwt-decode";
export default {
  
  name: 'app',
  props: {
    userList2: {
      type: Array,
      default: () => []
    }
  },
  data() {
    
    return {
      user: {},
      componentKey: 0,
      userList: this.userList2,
      
    };
  },
  
  created () {
    // get socket somehow
    socket.on('update', function (users){
      console.log(this.userList)
      this.userList = users;
      console.log(this.userList)
    }) 
  },
  methods: {
    async getUserDetails() {
      let token = localStorage.getItem("jwt");
      let decoded = VueJwtDecode.decode(token);
      let response = await this.$http.post("/update", decoded);
      let urank = response.data.rank;
      this.user = decoded;
      this.user.rank = urank;
    },
    logUserOut() {
      localStorage.removeItem("jwt");
      this.$router.push("/");
    },
    
  },
}
</script>

如何让 Vue bootstrap 组项目在 socket.io 发生更改后自动更新?

这有点难说,因为我们无法 运行 您的代码,但快速浏览一下我认为它就这么简单:

v-for="value in userList2"中的userList2替换为userList

如果你打算更多地使用套接字和 Vue,我认为 vue-socket.io 是一个非常有用的库: https://www.npmjs.com/package/vue-socket.io

概览:

您可以 $emit event 将更新后的列表返回给父组件,然后更新父组件中的 data 属性。那是因为你不应该直接修改 props.


示例:

在您的子组件中:

import io from 'socket.io-client';

data() {
 return {
  socket: io()
 }
},
props: {
 userList2: {
  type: Array,
  default: () => []
 }
},
created() {
  this.socket.on('update', (users) => {
   this.$emit('updateListEv', users);
  })
}

然后在你的父组件中:

<childNameComponent @updateListEv="updateList"></childNameComponent>

那么您需要在父组件中使用一种方法来使用从子组件传回的数据实际更新 data 属性。

methods: {
  updateList(updatedList) {
   this.userList2 = updatedList
  }
}

注:

如果您这样做,您应该可以直接使用 prop,因此无需在子组件中设置额外的 data 属性 - userList: this.userList2.

在这种情况下,您将遍历 userList2 - 与您现在正在做的方式相同 - v-for="value in userList2"

您还可以看到,在这种情况下,我们将套接字初始化为 data 属性 以便我们可以在 Vue 实例中使用它。


编辑:

import io from 'socket.io-client';
data() {
  return {
    socket: io(),
    usersList: this.userList2
  }
},
props: {
 userList2: {
  type: Array,
  default: () => []
 }
},
created() {
  this.socket.on('update', (users) => {
   this.userList = users
  })
}

在您的 HTML 模板循环中遍历用户列表:

v-for="value in usersList"

将 socket.io 与 Vue.js 和 Node.js 结合使用完整示例:

在您的后端 (Node.js):

//setting up sockets
const app = express()
const server = http.createServer(app)
const io = require('socket.io')(server)
io.on('connection', (socket) => {
  socket.on('sendUpdateList', function(data) {
    io.emit('listUpdate', data)
  });
})

正在从组件发送更新:

import io from 'socket.io-client';

data() {
 return {
  socket: io(),
  usersList: []
 }
},
methods: {
 this.socket.emit('sendUpdateList', {usersList: this.usersList})
}

监听组件中的socket:

import io from 'socket.io-client';

data() {
 return {
  socket: io(),
  usersList: []
 }
},
created() {
  this.socket.on('listUpdate', (data) => {
   this.usersList = data.usersList
  })
}

socket.on('update'回调里面的this不是你想的那样(不是vue组件),所以赋值给this.userList不会触发任何变化在 vue 组件中)。

使用箭头函数作为回调,这样它就可以像这样使用周围的 this(这是您的组件):

import io from 'socket.io-client';
import $ from 'jquery'
import VueJwtDecode from "vue-jwt-decode";

var socket = io('http://localhost:4000');

export default {
  name: 'app',
  props: {
    userList2: {
      type: Array,
      default: () => []
    }
  },
  data() {
    
    return {
      user: {},
      componentKey: 0,
      userList: this.userList2,
      
    };
  },
  
  created () {
    socket.on('update', users => {      // arrow function here so 'this' keyword inside will refer to your vue component
      this.userList = users;            // either this one
      this.userList2 = users;           // or this one (I don't know why you are using two props for this btw)
    }) 
  },
  // ...
}

阅读更多关于 this 的内容以及为什么箭头函数在另一个 SO 问题中没有它们:How does the "this" keyword work?