VueJS - Mixin



Mixin 對於與元件一起使用基本有用。它們在元件中共享可重用程式碼。當元件使用 mixin 時,mixin 的所有選項都成為元件選項的一部分。

示例

<html>
   <head>
      <title>VueJs Instance</title>
      <script type = "text/javascript" src = "js/vue.js"></script>
   </head>
   <body>
      <div id = "databinding"></div>
      <script type = "text/javascript">
         var vm = new Vue({
            el: '#databinding',
            data: {
            },
            methods : {
            },
         });
         var myMixin = {
            created: function () {
               this.startmixin()
            },
            methods: {
               startmixin: function () {
                  alert("Welcome  to mixin example");
               }
            }
         };
         var Component = Vue.extend({
            mixins: [myMixin]
         })
         var component = new Component();
      </script>
   </body>
</html>

輸出

Mixins

當 mixin 和元件包含重疊選項時,它們會合併到一起,如下面的示例所示。

<html>
   <head>
      <title>VueJs Instance</title>
      <script type = "text/javascript" src = "js/vue.js"></script>
   </head>
   <body>
      <div id = "databinding"></div>
      <script type = "text/javascript">
         var mixin = {
            created: function () {
               console.log('mixin called')
            }
         }
         new Vue({
            mixins: [mixin],
            created: function () {
               console.log('component called')
            }
         });
      </script>
   </body>
</html>

現在,mixin 和 vue 例項具有相同的方法 created。這是我們在控制檯中看到的結果。如您所見,vue 的選項和 mixin 將被合併。

Mixin Overlapping

如果碰巧我們在 methods 中具有相同的方法名稱,那麼主要的 vue 例項將享有優先權。

示例

<html>
   <head>
      <title>VueJs Instance</title>
      <script type = "text/javascript" src = "js/vue.js"></script>
   </head>
   <body>
      <div id = "databinding"></div>
      <script type = "text/javascript">
         var mixin = {
            methods: {
               hellworld: function () {
                  console.log('In HelloWorld');
               },
               samemethod: function () {
                  console.log('Mixin:Same Method');
               }
            }
         };
         var vm = new Vue({
            mixins: [mixin],
            methods: {
               start: function () {
                  console.log('start method');
               },
               samemethod: function () {
                  console.log('Main: same method');
               }
            }
         });
         vm.hellworld();
         vm.start();
         vm.samemethod();
      </script>
   </body>
</html>

我們將看到 mixin 中有一個方法屬性,其中定義了 helloworld 和 samemethod 函式。與此類似,vue 例項具有一個 methods 屬性,其中定義了其他兩個方法 start 和 samemethod。

將呼叫下面每種方法。

vm.hellworld(); // In HelloWorld
vm.start(); // start method
vm.samemethod(); // Main: same method

正如上面看到的那樣,我們已呼叫 helloworld、start 和 samemethod 函式。samemethod 也存在於 mixin 中,但是將優先考慮主例項,如以下控制檯所示。

Mixin as Method
廣告