js之websocket在vue项目中使用

 

websocket的大致作用

对于前端工程师来说,一般是前端通过触发事件,主动发起请求来获取后台数据。但是特定情况下,需要后端服务器主动推送数据到前端。这时候普通的axios等请求是无法实现的,websocket恰好可以实现这个需求。

 

<template>
  <div class="testIndex">
      <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="活动名称">
                <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">立即发送</el-button>
                <el-button>取消</el-button>
            </el-form-item>
      </el-form>

      <div class="">
          <h1>接收到的消息:</h1>
            <p v-for="(i,index) in receiveMsg" :key="index">{{i}}</p>

      </div>
  </div>
</template>

<script>
export default {
    data(){
        return{
            socket:{},//socket创建实例对象
            path:'ws://10.10.77.88:64494/ws',//需要连接的地址
            form:{
                name:''
            },
            receiveMsg:[],
        }
    },
    created(){
        this.init();
    },
    methods:{
            init(){
                if(typeof(WebSocket) === "undefined"){
                    alert("您的浏览器不支持socket")
                }else{
                    // 实例化socket
                    this.socket = new WebSocket(this.path)
                    // 监听socket连接
                    this.socket.onopen = this.open
                    // 监听socket错误信息
                    this.socket.onerror = this.error
                    // 监听socket消息
                    this.socket.onmessage = this.getMessage
                }
            },
            open(){
                console.log("连接成功")
            },
            error(){
                 console.log("连接错误")
            },
            getMessage(res){
                console.log("收取到的信息",res)
                this.receiveMsg.push(res.data)
            },
            //发送信息
            onSubmit(){
                console.log(this.form.name)
                this.socket.send(this.form.name)
            },
    }
}
</script>

<style lang="less">
    .testIndex{
        width: 100%;
        height: 100%;
        background: white;
    }
</style>

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值