如何:Vue3 组合 API 插件 [英] How to: Vue3 composition API plugin
问题描述
如何创建与 Vue3 组合 API 配合使用的插件.
How to create a plugin that works with the Vue3 composition API.
例如可以在每个组件中访问的 Socket.io 插件.
For example a Socket.io plugin which can be accessed in every component.
推荐答案
为 vue3 创建任何插件(例如:Socket.io)并在您的组合 API 组件和您的 vue2/option api 组件中使用它.
To create any plugin (example: Socket.io) for vue3 and use it in your composition API component and in your vue2/option api component.
创建插件本身并将其添加到您的plugins
文件夹
Create the plugin itself and add it to your plugins
folder
使用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 中添加以下内容
In your main.js add the following
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
来访问socket
In the option api you can use this.$socket
to access the 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 中,您还可以注入插件
In the option api you also have the possibility to inject the plugin
<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>
Composition API inject
在组合 API 中你应该使用 inject
In the composition API your should use 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>
这篇关于如何:Vue3 组合 API 插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!