如何创建与Vue3组合API一起工作的插件。
例如,可以在每个组件中访问的Socket.io插件。
发布于 2020-11-11 07:48:23
要为Socket.io创建任何插件(例如: vue3 ),并在复合API组件和vue2 2/option组件中使用它。
创建插件并将其添加到plugins文件夹中
使用Socket.io 3.0.1
插件:
import { io } from 'socket.io-client'
export default {
install: (app, { connection, options }) => {
const socket = io(connection, options)
app.config.globalProperties.$socket = socket
app.provide('socket', socket)
}
}在main.js中添加以下内容
import Socketio from '@/plugins/Socket.io'
app.use(Socketio, {
connection: 'http://localhost:4001',
options: {
// Your Socket.io options here
}
})main.js示例
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import Socketio from '@/plugins/Socket.io'
const app = createApp(App)
app.use(store)
app.use(router)
app.use(Socketio, {
connection: 'http://localhost:4001',
options: {
// Your Socket.io options here
}
})
app.mount('#app')用法:
选项API: this
在选项api中,可以使用this.$socket访问套接字。
<template>
// HTML here
</template>
<script>
export default {
mounted () {
// You can use the socket like shown below
this.$socket.on('foo', () => {
console.log('bar')
})
}
}
</script>选项API: inject
在选项api中,您还可以使用注入插件。
<template>
// HTML here
</template>
<script>
import { inject } from 'vue'
export default {
mounted () {
const socket = inject('socket')
// You can use the socket like shown below
socket.on('foo', () => {
console.log('bar')
})
}
}
</script>组合API inject
在复合API中,应该使用inject。
<template>
{{ bar }}
</template>
<script>
import { ref, inject } from 'vue'
export default {
setup() {
const socket = inject('socket')
return { ...foo(socket) }
}
}
function foo(socket) {
const bar = ref('')
socket.on('foo', (value) => {
bar.value = value
})
return {
bar
}
}
</script>https://stackoverflow.com/questions/64782385
复制相似问题