この内容は古いバージョンです。最新バージョンを表示するには、戻るボタンを押してください。
バージョン:3
ページ更新者:guest
更新日時:2019-08-25 18:51:57

タイトル: Mixinを利用した共通処理の記述方法
SEOタイトル: 【Vue.js】Mixinを利用した共通処理の記述方法

この記事の要点
  • Vue.js の Mixin: 複数コンポーネントで共通処理を流用する仕組み
  • 共通処理を別ファイル (Common.vue) に export default {...} で書く
  • 使う側で import Common from "./Common.vue"mixins: [Common] を宣言
  • Vue 3 はComposition API(useXxx() 関数)のほうが推奨される

 

共通の処理

共通処理用のvueファイルを作成して以下の様に共通化したい処理を記述する。

内容はなんでもよい。

Common.vue
<script>
    export default {
        created() {
            this.getMessages()
        },
        data() {
            return {
                messages: [],
            }
        },
        methods: {
            getMessages() {
                axios
                    .get('/api/message/list')
                    .then(res =>  {
                        this.messages = res.data
                    })
            },
        }
    }
</script>

 

 

共通処理を呼び出す処理

mixinsを使用して引数に共通処理のファイルを指定する。

Example.vue

<script>
   
import Common from './Common.vue'

    export default {
       
mixins: [Common],
        created() {
            this.getChannelsTest()
        },
        data() {
            return {
                channels: [],
            }
        },
        methods: {
            getChannelsTest() {
                axios
                    .get('/api/channels/test')
                    .then(res =>  {
                        this.channels = res.data
                    })
            },
        }
    }
</script>

 

共通処理を呼び出す処理を省略する方法

全ての処理で使う場合はmain.jsで指定すればよい。

そうすれば各コンポーネント内で呼び出す必要もなくなる。

main.js

import Common from './Common.vue'

Vue.mixin(Common)

new Vue({
  el: '#app',
  router,
  render: h => h(App),
})