16-Vue之混入mixin的使用

Vue之混入mixins(非完整版)

一、mixins基礎(chǔ)介紹(不使用cli版本)

1.首先我們看一下vue官網(wǎng)對(duì)mixin的介紹:

混入 (mixin) 提供了一種非常靈活的方式,來(lái)分發(fā) Vue 組件中的可復(fù)用功能。一個(gè)混入對(duì)象可以包含任意組件選項(xiàng)。當(dāng)組件使用混入對(duì)象時(shí),所有混入對(duì)象的選項(xiàng)將被“混合”進(jìn)入該組件本身的選項(xiàng)。

這里先列出一個(gè)小小的栗子我們來(lái)看一下

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <!-- 這里引入下載下來(lái)的vue.js -->
  <script src="../vue.js"></script>
  <script>
    // 定義一個(gè)混入對(duì)象
    var myMixin = {
      created: function () {
        this.hello()
      },
      methods: {
        hello: function () {
          console.log('hello from mixin!')
        }
      }
    }
    // 定義一個(gè)使用混入對(duì)象的組件
    var Component = Vue.extend({
      mixins: [myMixin]
    })
    var component = new Component() // => "hello from mixin!"  
  </script>
</body>
</html>

這里我們大致知道m(xù)ixin混入到底是怎么去使用的

  • 首先我們要先去定義需要混入的對(duì)象myMixin
  • 然后在需要引入的組件中去引用mixins: [myMixin]

2.選項(xiàng)合并

簡(jiǎn)單的來(lái)說(shuō)就是,組件里使用mixin,但組件和mixin中都定義了相同的數(shù)據(jù)屬性,數(shù)據(jù)對(duì)象在內(nèi)部會(huì)進(jìn)行遞歸合并,并在發(fā)生沖突時(shí)以組件數(shù)據(jù)優(yōu)先。

舉個(gè)栗子吧

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <!-- 這里引入下載下來(lái)的vue.js -->
  <script src="../vue.js"></script>
  <script>
        // 老樣子這里定義一個(gè)mixin
        var mixin = {
            data: function () {
                return {
                    message: 'hello',
                    foo: 'abc'
                }
            }
        }
        // 這里就作為組件
        new Vue({
            // 然后在組件中使用
            mixins: [mixin],
            data: function () {
                return {
                    message: 'goodbye',
                    bar: 'def'
                }
            },
            created: function () {
                console.log(this.$data)
                // => { message: "goodbye", foo: "abc", bar: "def" }
            }
        })
  </script>
</body>
</html>

最后結(jié)果會(huì)發(fā)現(xiàn)mixin中定義的數(shù)據(jù)message,并未被打印出來(lái),使用的還是組件中定義的message

那么我相信有不少同學(xué)可能會(huì)問(wèn),mixin和組件里面誰(shuí)的鉤子函數(shù)先被使用呢?

我們接下來(lái)再來(lái)看一個(gè)栗子

var mixin = {
  created: function () {
    console.log('混入對(duì)象的鉤子被調(diào)用')
  }
}

new Vue({
  mixins: [mixin],
  created: function () {
    console.log('組件鉤子被調(diào)用')
  }
})

上面這個(gè)組件里面使用了Mixin,打開(kāi)控制臺(tái),到底是哪一個(gè)先被打印呢

// => "混入對(duì)象的鉤子被調(diào)用"
// => "組件鉤子被調(diào)用"

結(jié)果是:同名鉤子函數(shù)將合并為一個(gè)數(shù)組,因此都將被調(diào)用。另外,混入對(duì)象的鉤子函數(shù)將在組件自身鉤子函數(shù)之前調(diào)用。

那有同學(xué)可能就會(huì)聯(lián)想到其他屬性方法呢,比如methods、compoents,如果相同會(huì)怎么樣,mixin和組件里面誰(shuí)的會(huì)被調(diào)用呢?

嘿嘿,老規(guī)矩我們?cè)賮?lái)看一個(gè)栗子

var mixin = {
  methods: {
    foo: function () {
      console.log('foo')
    },
    conflicting: function () {
      console.log('from mixin')
    }
  }
}

var vm = new Vue({
  mixins: [mixin],
  methods: {
    bar: function () {
      console.log('bar')
    },
    conflicting: function () {
      console.log('from self')
    }
  }
})

vm.foo() // => "foo"
vm.bar() // => "bar"
vm.conflicting() // => "from self"

這個(gè)結(jié)果是不是在大家的意料范圍之內(nèi),沒(méi)錯(cuò),值為對(duì)象的選項(xiàng),例如 methods、componentsdirectives,將被合并為同一個(gè)對(duì)象。兩個(gè)對(duì)象鍵名沖突時(shí),取組件對(duì)象的鍵值對(duì)。

3.全局混入

嚴(yán)重警告:一旦使用全局混入,它將影響每一個(gè)之后創(chuàng)建的 Vue 實(shí)例。使用恰當(dāng)時(shí),這可以用來(lái)為自定義選項(xiàng)注入處理邏輯。

// 為自定義的選項(xiàng) 'myOption' 注入一個(gè)處理器。
Vue.mixin({
  created: function () {
    var myOption = this.$options.myOption
    if (myOption) {
      console.log(myOption)
    }
  }
})

new Vue({
  myOption: 'hello!'
})
// => "hello!"

咦,我只是在官網(wǎng)上看到了,好像現(xiàn)在基本上都不用全局混入,因?yàn)橐坏┦褂貌划?dāng)就會(huì)出大問(wèn)題哦。

二、一些容易混淆的東西

1.同時(shí)引入多個(gè)mixin對(duì)象,到底是哪個(gè)先被使用呢

老規(guī)矩,看栗子

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <!-- 這里引入下載下來(lái)的vue.js -->
    <script src="../vue.js"></script>
    <script>
        //兩個(gè)mixins對(duì)象
        const mixinsTest = {
            methods: {
                hello() {
                        console.log("hello mixins");
                }
            },
            created() {
                this.hello();
            },
        }
        const mixinsTest2 = {
            methods:{
                hello2(){
                    console.log("hello2");
                }
            },
            created() {
                this.hello2();
            },
        }
    </script>
  <script>
    // 定義一個(gè)使用混入對(duì)象的組件
    var Component = Vue.extend({
            // 引入多個(gè)混入對(duì)象
      mixins: [mixinsTest2,mixinsTest]
    })
    var component = new Component() // => "hello2 hello mixins"  
  </script>
</body>
</html>

我們會(huì)發(fā)現(xiàn)我們引入多個(gè)以后,我們mixins: [mixinsTest2,mixinsTest],我們先引入的先被使用

先引用,先使用!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容