巷で話題の(?)Lightning Web Components(LWC)をVisualforceで表示できないか試してみました。
LWCをAura Componentでラップして、Lightning Outを使う
最初に思いついたのは、LWCをAura Componentでラップして、Lightning Out for Visualforceを使う方法です。
この方法で問題なく表示できました。
ソースを順に見ていきます。
LWC
Trailheadのサンプルのまんまですが…。
■ helloworld.html
<template> <lightning-card title="HelloWorld" icon-name="custom:custom14"> <div class="slds-m-around_medium"> <p>Hello, {greeting}!</p> <lightning-input label="Name" value={greeting} onchange={changeHandler}></lightning-input> </div> </lightning-card> </template>
■ helloworld.js
import { LightningElement, track } from 'lwc'; export default class HelloWorld extends LightningElement { @track greeting = 'World'; changeHandler(event) { this.greeting = event.target.value; } }
Aura Component (auraHelloWorld.cmp)
LWCを呼び出すだけ。
<aura:component implements="flexipage:availableForAllPageTypes"> <c:helloworld /> </aura:component>
参考にしたのは以下のページです:
Compose Aura Components from Lightning Web Components
Lightning Outアプリケーション(helloWorldOut.app)
上記のAura Componentを使えるように宣言します。
<aura:application extends="ltng:outApp" > <aura:dependency resource="c:auraHelloWorld" /> </aura:application>
Visualforce (lwcHelloWorld.vfp)
ページ名(ファイル名)は何でもよいです。
<apex:page> <apex:includeLightning /> <div id="hello"></div> <script> $Lightning.use("c:helloWorldOut", function() { $Lightning.createComponent("c:auraHelloWorld", {}, "hello", function(cmp, err) {}); }); </script> </apex:page>
プレビュー
できました!
Aura Componentでラップする必要ないのでは?
ところで、よくよく考えると、Aura Componentでラップする必要がないのでは?という疑問が湧きました。
というわけで、Lightning Outアプリケーションで直接LWCを宣言します。
<aura:application extends="ltng:outApp" > <aura:dependency resource="c:helloworld" /> </aura:application>
その後、Visualforce側 createComponent の引数も "c:helloworld"
に変更します。こちらの方法でも、同じように表示できました。
まとめ
LWCをVisualforceで表示したければ、今までのAura Componentと同じ要領でLightning Outが利用できます。
注:今回は簡単なサンプルだけなので、実際にやると色んな落とし穴があるかもしれません。