老项目是基于Vue.js 2 开发的, 开发体验不如 Vue.js 3. 不过, Vue 2的最后一个版本 2.7 已经为开发者扫清了大部分障碍, 能很好的兼容版本3的用法, 为老项目升级提供了一条丝滑的过渡带.
在 Vue 2.7 中, 也可以使用 <script setup>
语法以及 Composable API. Vue 3 中的ref
,computed
, onMounted
, Vue 2.7 都支持.
这样, 在 Vue 2 中, 也能摆脱Vue实例( this )的束缚. 如果实在需要用 Vue 实例, 也可以用 getCurrentInstance
来获取. 例如可以这样使用 VueSocketIO:
export function useSocket() {
const instance = getCurrentInstance();
if (!instance) {
throw new Error(`useSocket should be called in setup().`);
}
return instance.proxy.$socket;
}
export function useSockets() {
const instance = getCurrentInstance();
if (!instance) {
throw new Error(`useSocket should be called in setup().`);
}
return instance.proxy.sockets;
}
在组件中,可以这样使用
<script setup>
const socket = useSocket();
const sockets = useSockets();
socket.emit(event, data);
sockets.subscribe(event,handler);
onUnmounted(() => {
sockets.unsubscribe(event);
});
</script>