1. 程式人生 > 其它 >[轉]vue 中 mixins 的使用

[轉]vue 中 mixins 的使用

mixins(混入)就是定義了一部分公共的方法、計算屬性或者鉤子函式等 vue 元件中的可複用功能,然後混合進各個元件中使用。下面我們具體來看看怎麼使用。

建立一個 demo.js 檔案,然後 export 給外部使用

export const demoMixins = {
    data() {
        return {
            name: '我是 mixins 中的字串 name',
            user: '我是 mixins 中的字串 user'
        }
    },
    created() {
        console.log('我是 mixins 中的鉤子函式 created')
        this.hello()
        this.say()
        this.pay()
    },
    methods: {
        hello() {
            console.log('我是 mixins 中的函式 hello')
        },
        say() {
            console.log('我是 mixins 中的函式 say')
        }
    }
}

在元件中引入這個 mixins 物件

<template>
    <div></div>
</template>

<script>
import { demoMixins } from '@/mixins/demo'
export default {
    mixins: [demoMixins],
    data() {
        return {
            name: '我是元件中的字串 name',
            sex: '我是元件中的字串 sex'
        }
    },
    created() {
        console.log('我是元件中的鉤子函式 created')
        this.hello()
        this.say()
        this.pay()
    },
    methods: {
        hello() {
            console.log('我是元件中的函式 hello')
        },
        pay() {
            console.log('我是元件中的函式 pay')
        }
    }
}
</script>

我們先來看看執行結果

// => 我是 mixins 中的鉤子函式 created
// => 我是元件中的函式 hello
// => 我是 mixins 中的函式 say
// => 我是元件中的函式 pay
// => 我是元件中的鉤子函式 created
// => 我是元件中的函式 hello
// => 我是 mixins 中的函式 say
// => 我是元件中的函式 pay

總結

  • 混入物件的鉤子將在元件自身鉤子之前呼叫。
  • 值為物件的選項,例如 datamethodscomponentsdirectives,將被合併為同一個物件。兩個物件鍵名衝突時,取元件物件的鍵值對。
  • 混入物件中可以使用和呼叫元件自身變數和函式,且與在元件自身中使用情況一樣。
思考:一個元件是否可以同時引入多個 mixins?如果可以,執行結果和順序又會是怎樣的?大家有興趣可以自己動手試試看。