Vue.jsを使用したネイティブWebコンポーネントの構築
Webコンポーネント/カスタム要素の仕様を使用すると、ブラウザーで独自のカスタム要素とそれに接続されているロジックを定義できます。 久しぶりですが、もうすぐです。 Webコンポーネントの利点は、任意のフレームワークやライブラリ、さらにはVanillaJSの間で相互運用できることです。 Vueのの小さいサイズのおかげで、プラグインの助けを借りて、Vueコンポーネントからネイティブのカスタム要素を作成できます。
インストール
Vueカスタム要素には(適切な名前の)vue-custom-elementプラグインが必要です。
ヤーンまたはNPMを介してインストールします。
# Yarn
$ yarn add vue-custom-element -D
# NPM
$ npm install vue-custom-element --save-dev
さらに、Chrome専用にビルドしているのでない限り、おそらくdocument-register-elementポリフィルが必要になります。
Webコンポーネントの作成
通常どおりにコンポーネントを記述します。ビルドシステムを使用している場合、単一ファイルのコンポーネントは正常に機能します。
ExampleComponent.vue
<template>
<p>Dynamic prop value: {{myProp}}</p>
</template>
<script>
export default {
props: ['myProp']
}
</script>
次に、 vue-custom-element プラグインをVueに追加し、コンポーネントを登録します。
main.js
import Vue from 'vue';
import vueCustomElement from 'vue-custom-element';
import ExampleComponent from './ExampleComponent.vue';
// Configure Vue to ignore the element name when defined outside of Vue.
Vue.config.ignoredElements = [
'example-component'
];
// Enable the plugin
Vue.use(vueCustomElement);
// Register your component
Vue.customElement('example-component', ExampleComponent, {
// Additional Options: https://github.com/karol-f/vue-custom-element#options
});
これで、スタンドアロンスクリプトを作成した後、そのスクリプトを任意のWebページに追加して、期待どおりにexample-componentをレンダリングできるようになります。
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Example Vue Page</title>
<script src="dist/build.js" async deferred></script>
</head>
<body>
<example-component myProp="I can pass props!"></example-component>
</body>
</html>
文字列以外の値を渡すことはできませんが、小道具は引き続き反応します。
そして、あなたはそれを持っています! Vueで作られたカスタム要素!