LoginSignup
5
11

More than 3 years have passed since last update.

VueでJsの中に静的と動的に外部Jsを読み込む書き方

Last updated at Posted at 2019-05-23

Vueプロジェクトを開発する際に、利用中のJsの中で、そのたのJsについてのファンクションやオブジェクトをインポートして利用することがよくあります。外部のJsをインポートするときには、静的にと動的に二つの方法があります。以下で簡単に説明してみます。

例文

index.vue
<template>
  <div>
  <p>{{ msg }}</p>
  </div>
</template>
<script>
import { t3m1 } from './t3'
export default {
  name: 'test',
  data () {
    return {
      msg: 'you are ok.'
    }
  },
  mounted () {
    t3m1()
  }
}
</script>
t1.js
const t1m1 = function () {
  console.log('t1m1 ok')
}
function t1m2 () {
  console.log('t1m2 ok')
}
export { t1m1, t1m2 }
t2.js
const t2 = {}
t2.t2m1 = function () {
  console.log('t2m1 ok')
}
t2.t2m2 = function () {
  console.log('t2m2 ok')
}
export default { t2 }
t3.js
// 外部Jsを静的に読み込む書き方
import t2 from './t2'
function t3m1 () {
  console.log('t3m1 ok')
  // 外部Jsを動的に読み込む書き方
  import('./t1.js').then((t1) => {
    t1.t1m1()
  })
  t2.t2.t2m1()
}
export { t3m1 }

実行結果

無題.png

5
11
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
5
11