現在、独学でLaravel、Vue.jsを使ってWEBサービス開発の練習をしています。
プログラミングの勉強は1年ほどになりますが、LaravelとVue.jsは2ヶ月ほど触っただけの超素人です。
最初に結論
laravelでVue Componentを書いたらresources/js/app.js
に登録する。
でないと、コンソールに
Unknown custom element: <chart> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
(コンポーネントが正しく登録されてないよ)とエラーが出る。
状況
上のような温泉レビュー掲示板を作成中。
vue-chartjsでレーダーチャートを作成。
このレーダーチャート部分をコンポーネント化したく、resources/js/components/Chart.vue
を作成。
<script>
import { Radar } from 'vue-chartjs'
export default {
extends: Radar,
data () {
return {
data: {
labels: ["総合", "温泉", "街並み", "グルメ", "アクセス"],
datasets: [{
data: [5, 4, 3, 2, 1],
backgroundColor: 'rgba(255, 234, 42, 0.8)',
borderColor: 'rgba(255, 234, 42, 0.8)',
borderWidth: 1,
pointRadius:0
}]
},
options: {
title: {
display: true
},
legend: {
display: false
},
scale:{
ticks:{
suggestedMin: 0,
suggestedMax: 5,
stepSize: 1,
callback: function(value, index, values){
return value
}
}
}
}
}
},
mounted () {
this.renderChart(this.data, this.options)
}
}
</script>
<style>
</style>
次に、温泉個別ページ(show.blade.php
)からコンポーネントを呼び出す。
<div id="app" class="chart">
<chart></chart>
</div>
コンソールにエラーが出ている。
Unknown custom element: <chart> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
よう分からんコンポーネントがありますよ。正しく登録しました?とのこと。
調べてみると、vueファイルはresources/js/app.js
に登録して初めて、コンポーネントとして使えるようだ。(仕組みは分かっていないので勉強していきます。)
とにかく、resources/js/app.js
を確認してみる。
/**
* The following block of code may be used to automatically register your
* Vue components. It will recursively scan this directory for the Vue
* components and automatically register them with their "basename".
*
* Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
*/
// const files = require.context('./', true, /\.vue$/i);
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default));
Vue.component('example-component', require('./components/ExampleComponent.vue').default);
次のコードを書いたらあなたのVue componentが自動的に登録されます。とのこと。
It will recursively~は何のこっちゃ、さっぱりわかりません。
とりあえず、既にExampleComponent.vueが既に登録されていたので、それに倣ってChart.vueも登録します。
/**
* The following block of code may be used to automatically register your
* Vue components. It will recursively scan this directory for the Vue
* components and automatically register them with their "basename".
*
* Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
*/
// const files = require.context('./', true, /\.vue$/i);
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default));
Vue.component('example-component', require('./components/ExampleComponent.vue').default);
Vue.component('chart', require('./components/Chart.vue').default);
もう一度画面を確認すると、レーダーチャートが表示されました!
最後に
こういった基本的なことすら、まだまだ知らないことばかりです。頑張らねば。