1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

vue3のmyPluginをtypescriptで作る

Posted at

nuxt3jsの場合もほぼ同じような作りです。

以下のようなtslintが反応する場合は、declare moduleが足りてない。

プロパティ '$myPlugin' は型 '{ $: ComponentInternalInstance; ...' に存在しません。ts(2339) 
main.ts
import App from '@/App.vue';
import { createApp } from 'vue';

import myPlugin from '@/plugins/myPlugin'

const app = createApp(App);
app.use(myPlugin);

app.mount('#app');
plugins/myplugin.ts
import { type Plugin } from 'vue';

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $myPlugin: (msg: string) => string;
  }
}

const myFunctions = (key: string) => key + ':myplugin';

// for vue template
const myPlugin: Plugin = {
  install (app, options?: { [key: string]: any }) {
    app.config.globalProperties.$myplugin = (key: string) => myFunctions(key);
    app.provide('$myplugin', options);
  }
};

// for composables
export const $myplugin = (key: string): string => myFunctions(key);

export default myPlugin;
index.vue
<script setup lang="ts">
import { $myPlugin } from '@/plugins/myPlugin'
console.log($myplugin('aaa'))
</script>

<template>
  <div> {{ $myplugin('aaa') }} </div>
</template>
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?