index.vue 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <template>
  2. <view class="">
  3. <chat-room
  4. :chats="chats"
  5. @send="send"
  6. />
  7. </view>
  8. </template>
  9. <script>
  10. import ChatRoom from '@/components/IM/index.vue';
  11. import {rongcloudInit,sendMsg,connect} from '@/libs/rongcloud';
  12. import {deepClone} from '@/libs';
  13. export default {
  14. components:{
  15. ChatRoom
  16. },
  17. data() {
  18. return {
  19. chats:[],
  20. communicatorId:"",
  21. communicatorName:""
  22. }
  23. },
  24. created() {
  25. this.initChat();
  26. },
  27. onLoad({id,name}) {
  28. this.communicatorId=id;
  29. this.communicatorName=name;
  30. },
  31. methods: {
  32. //客户端连接服务器
  33. initChat(){
  34. rongcloudInit({
  35. receiveMsg:(info)=>{
  36. this.receive(info)
  37. },
  38. status(evt){
  39. console.log('聊天室状态:'+evt.status)
  40. }
  41. });
  42. let user=uni.getStorageSync('accountInfo');
  43. if(user){
  44. let imToken=user.imToken;
  45. connect({
  46. token:imToken
  47. });
  48. }
  49. },
  50. send(sendmessage){
  51. let chats=deepClone(this.chats);
  52. let targetId=this.communicatorId;
  53. sendMsg({sendmessage,targetId}).then((res)=>{
  54. let info=res.content.content;
  55. chats.push({
  56. msg:info,
  57. type:'mine',
  58. user:'自己'
  59. })
  60. this.chats=chats;
  61. }).catch((error)=>{
  62. chats.push({
  63. msg:"消息发送失败",
  64. type:'system',
  65. user:'系统'
  66. })
  67. })
  68. },
  69. receive(info){
  70. console.log("收到消息")
  71. let chats=deepClone(this.chats);
  72. let name=this.communicatorName;
  73. console.log({
  74. msg:info.content.content,
  75. type:'receive',
  76. user:name
  77. })
  78. chats.push({
  79. msg:info.content.content,
  80. type:'receive',
  81. user:name
  82. })
  83. this.chats=chats;
  84. }
  85. }
  86. }
  87. </script>
  88. <style lang="scss" scoped>
  89. @import url('./index.css')
  90. </style>