Vue中使用WebSocket實現前後端實時通訊

一、使用TypeScript配置Vue項目

在Vue項目中使用TypeScript,需要先進行相關配置,以下是一些基本配置:


// 安裝相關依賴
npm install --save-dev typescript ts-loader

// 添加vue-shim.d.ts文件
declare module "*.vue" {
  import Vue from "vue";
  export default Vue;
}

接下來,需要在webpack.config.js文件中添加相關配置:


// 引入webpack模塊
const webpack = require('webpack');

module.exports = {
  entry: './src/index.ts',
  output: {
    filename: 'bundle.js',
    path: __dirname + '/dist'
  },
  resolve: {
    extensions: ['.ts', '.js', '.vue', '.json'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    }
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        loader: 'ts-loader',
        exclude: /node_modules/,
        options: {
          appendTsSuffixTo: [/\.vue$/],
        }
      }
    ]
  },
  plugins: [
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery'
    })
  ]
};

二、前端Vue中使用WebSocket

1、使用Vue插件vue-native-websocket

第一種使用WebSocket的方法,是使用Vue插件vue-native-websocket。

首先需要在項目中安裝該插件:


npm install vue-native-websocket --save

接下來,在main.js文件中添加以下代碼:


import VueNativeSock from 'vue-native-websocket'
Vue.use(VueNativeSock, 'ws://localhost:8080/ws', {
  store: store,
  format: 'json',
  connectManually: true
})

上述代碼中,第一參數表示WebSocket的地址,第二個參數是個對象,包括store、format和connectManually等屬性。

接下來,在Vue組件中,可以這樣使用WebSocket:


import { mapState } from 'vuex'
export default {
  computed: {
    ...mapState({
      socket: state => state.socket.socket
    })
  },
  methods: {
    send () {
      const msg = JSON.stringify({type: 'message', data: this.msgToSend})
      this.socket.send(msg)
      this.msgToSend = ''
    }
  }
}

上述代碼中,通過computed屬性,將socket對象映射到組件中。send方法,可以向WebSocket伺服器發送數據。

2、手動實現WebSocket

在Vue項目中手動實現WebSocket,也是一種常見的做法。

首先,需要新建一個WebSocket Vue組件:


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

<script>
  export default {
    data () {
      return {
        ws: null
      }
    },
    mounted () {
      this.initWebsocket()
    },
    beforeDestroy () {
      this.closeWebsocket()
    },
    methods: {
      initWebsocket () {
        this.ws = new WebSocket('ws://localhost:8080/ws')
        this.ws.onopen = (event) => {
          console.log('open', event)
          this.sendMessage('hello world')
        }
        this.ws.onmessage = (event) => {
          console.log('message', event)
        }
        this.ws.onerror = (event) => {
          console.log('error', event)
        }
        this.ws.onclose = (event) => {
          console.log('close', event)
          this.ws = null
        }
      },
      closeWebsocket () {
        if (this.ws) {
          this.ws.close()
        }
      },
      sendMessage (message) {
        if (this.ws) {
          this.ws.send(message)
        }
      }
    }
  }
</script>

上述WebSocket組件,通過initWebsocket方法,初始化WebSocket的連接,通過sendMessage方法,向WebSocket伺服器發送數據,通過closeWebsocket方法,關閉WebSocket連接。

三、Vue中使用axios

1、axios發送GET請求

使用axios發送GET請求,需要引入axios,並調用其get方法。


import axios from 'axios'

axios.get('http://localhost:3000/users')
  .then(response => {
    console.log(response)
  })
  .catch(error => {
    console.log(error)
  })

上述代碼中,我們向http://localhost:3000/users發送了一個GET請求,並在成功或失敗時,分別列印了response或error。

2、axios發送POST請求

使用axios發送POST請求,需要調用axios的post方法。


import axios from 'axios'

axios.post('http://localhost:3000/users', {
    name: 'John Smith',
    age: '25'
  })
  .then(response => {
    console.log(response)
  })
  .catch(error => {
    console.log(error)
  })

上述代碼中,我們向http://localhost:3000/users發送了一個POST請求,並以JSON格式,向伺服器傳遞了一個{name: ‘John Smith’, age: ’25’}的對象。

3、axios攔截器

在axios中,攔截器是一種重要的概念。攔截器可以在請求或響應被處理前,對其進行攔截或處理。

以下是一個攔截器的示例代碼:


import axios from 'axios'

axios.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

上述代碼中,我們使用了axios的request攔截器,對請求進行了攔截,並在請求頭中添加了Authorization屬性。

原創文章,作者:EPBTW,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/332521.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
EPBTW的頭像EPBTW
上一篇 2025-01-24 18:46
下一篇 2025-01-24 18:46

相關推薦

  • 使用Vue實現前端AES加密並輸出為十六進位的方法

    在前端開發中,數據傳輸的安全性問題十分重要,其中一種保護數據安全的方式是加密。本文將會介紹如何使用Vue框架實現前端AES加密並將加密結果輸出為十六進位。 一、AES加密介紹 AE…

    編程 2025-04-29
  • Vue TS工程結構用法介紹

    在本篇文章中,我們將從多個方面對Vue TS工程結構進行詳細的闡述,涵蓋文件結構、路由配置、組件間通訊、狀態管理等內容,並給出對應的代碼示例。 一、文件結構 一個好的文件結構可以極…

    編程 2025-04-29
  • Cookie是後端生成的嗎?

    是的,Cookie通常是由後端生成並發送給客戶端的。下面從多個方面詳細闡述這個問題。 一、什麼是Cookie? 我們先來簡單地了解一下什麼是Cookie。Cookie是一種保存在客…

    編程 2025-04-28
  • Avue中如何按照後端返回的鏈接顯示圖片

    Avue是一款基於Vue.js、Element-ui等技術棧的可視化開發框架,能夠輕鬆搭建前端頁面。在開發中,我們使用到的圖片通常都是存儲在後端伺服器上的,那麼如何使用Avue來展…

    編程 2025-04-28
  • Vue3的vue-resource使用教程

    本文將從以下幾個方面詳細闡述Vue3如何使用vue-resource。 一、安裝Vue3和vue-resource 在使用vue-resource前,我們需要先安裝Vue3和vue…

    編程 2025-04-27
  • Vue模擬按鍵按下

    本文將從以下幾個方面對Vue模擬按鍵按下進行詳細闡述: 一、Vue 模擬按鍵按下的場景 在前端開發中,我們常常需要模擬按鍵按下的場景,比如在表單中填寫內容後,按下「回車鍵」提交表單…

    編程 2025-04-27
  • ThinkPHP6 + Vue.js: 不使用Fetch的數據請求方法

    本文將介紹如何在ThinkPHP6和Vue.js中進行數據請求,同時避免使用Fetch函數。 一、AJAX:XMLHttpRequest的基礎使用 在進行數據請求時,最基礎的方式就…

    編程 2025-04-27
  • 小波特掘金——從前端到後端的全棧開發之路

    本文將從小波特掘金平台的概述、前端和後端技術棧、以及實例代碼等多個方面來探討小波特掘金作為一個全棧開發工程師的必練平台。 一、平台概述 小波特掘金是一個前後端分離式的技術分享社區,…

    編程 2025-04-27
  • 開發前端程序,Vue是否足夠?

    Vue是一個輕量級,高效,漸進式的JavaScript框架,用於構建Web界面。開發人員可以使用Vue輕鬆完成前端編程,開發響應式應用程序。然而,當涉及到需要更大的生態系統,或利用…

    編程 2025-04-27
  • 後端介面設計開發經驗分享

    在受到前端某些限制或特殊需求時,後端介面的設計和開發顯得尤為重要。下面從以下幾個方面進行講述。 一、命名規範 合理的命名規範可以大大提高介面的可讀性和可維護性。以下是一些命名規範的…

    編程 2025-04-27

發表回復

登錄後才能評論