一、使用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