如何:Vue3 组合 API 插件

The*_*rkt 2 socket.io vue.js vuejs3 vue-composition-api

如何创建与 Vue3 组合 API 配合使用的插件。

例如可以在每个组件中访问的 Socket.io 插件。

The*_*rkt 10

为 vue3 创建任何插件(例如:Socket.io)并在你的组合 API 组件和你的 vue2/option api 组件中使用它。

创建插件本身并将其添加到您的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)
  }
}
Run Code Online (Sandbox Code Playgroud)

在您的main.js添加以下内容

import Socketio from '@/plugins/Socket.io'

app.use(Socketio, {
    connection: 'http://localhost:4001',
    options: {
        // Your Socket.io options here
    }
})
Run Code Online (Sandbox Code Playgroud)

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')
Run Code Online (Sandbox Code Playgroud)

用法:

选项 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>
Run Code Online (Sandbox Code Playgroud)

选项 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>
Run Code Online (Sandbox Code Playgroud)

组合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>
Run Code Online (Sandbox Code Playgroud)