LoginSignup
1
0

More than 3 years have passed since last update.

[Vue 3]app.config.globalPropertiesがundefinedと言われてしまった人の忘備録

Last updated at Posted at 2021-04-21

はじめに

Vue2から3にアップデートするにあたり、vue-xxx シリーズが片っ端から陳腐化してしまったため、
app.config.globalPropertiesに自分でプログラムを置くことにしました。
ところが、そこにちいさな躓きポイントが結構あったため忘備録として起きたことと解決までを記述してます。

環境

Vue ^3.0.5

↓今回入れたいアプリ↓
luxon ^1.26.0

問題発生

app.js
const {DateTime, Interval} = require("luxon");
import { createApp, h } from 'vue';
const el = document.getElementById('app');
let app = createApp({}).mount(el);

//Uncaught TypeError: Cannot read property 'globalProperties' of undefined
app.config.globalProperties.$luxonDateTime = DateTime;

app.configglobalPropertiesが無いよと言われている。

ますは仕様を確認

この解決法を見つけたのはStackoverflowの以下の記述だったので、重要な情報が抜けている可能性がある。
https://stackoverflow.com/questions/67029689/importing-vue-luxon-for-vue-v3-this-luxon-is-not-a-function-error

というわけで、本家Vue3さんに仕様を確認しに行く
https://v3.vuejs.org/api/application-config.html#globalproperties

どうやら間違いなく存在するようだ。

とりあえずconfigの中身を見てみる

上記ページの一番最初にconsole.log(app.config)で確認してみろと書いてあったのでやってみた。

app.js
//...

let app = createApp({}).mount(el);

console.log(app.config); //undefined

app.config.globalProperties.$luxonDateTime = DateTime;

なんと出力はundefinedだった。

なんか怪しいぞ?

仮にバージョンを間違えていた等の根本的な問題があったとしても、さすがにapp.configが空というのはおかしい。
そこで初めて、 createApp({}).mount(el)←これの戻り値がおかしいのではないか?と気が付く。

以下のように書き換えてみた。

app.js
//...

let app = createApp({});
app.mount(el);

console.log(app.config); //Object

出てきた!

解決

というわけで、今回の原因は、
app本体が入っていると思っていた変数にmount()の戻り値が入ってしまっており、期待した値ではなかった
でした。
ちゃんと関数の戻り値は確認しようね!

※componentの読み込み系はすべて省略しています。自分で増やしてください。

app.js
//..

let app = createApp({});
app.mount(el);

app.config.globalProperties.$luxonDateTime = DateTime;
app.config.globalProperties.$luxonInterval = Interval;
index.vue
//...
<script>
export default {
  name: "Index",
  data() {
    return {
      now: this.$luxonDateTime.now()
    }
  }
}
</script>

//..

無事動きました!!

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