专业的编程技术博客社区

网站首页 > 博客文章 正文

vue中的mixins混入(vue.mixin)

baijin 2024-09-23 03:46:25 博客文章 4 ℃ 0 评论

代码如下

<template>
  <div>
    <p class="aC" @click="fooM(),barM(),conflicting()">click</p>
    <p>{{message}}</p>
    <p>{{foo}}</p>
    <p>{{bar}}</p>
  </div>
</template>

<script>
  // 定义一个 mixin 对象
  const myMixin = {
    data() {
      return {
        // 属性冲突时以组件自身的数据优先
        message: 'hello',
        foo: 'abc'
      }
    },
    // 同名钩子函数将合并为一个数组,因此都将被调用。且mixin 对象的钩子将在组件自身钩子之前调用
    created() {
      alert('mixin 对象的钩子被调用');
    },
    /**
     * 值为对象的选项,例如 methods、components 和 directives,将被合并为同一个对象。
     * 两个对象键名冲突时,取组件对象的键值对
     * */ 
    methods: {
      fooM() {
        alert('fooM')
      },
      conflicting() {
        alert('mixin的键值对')
      }
    }
  }
  
  export default {
    mixins: [myMixin],
    created() {
      alert('组件自身钩子被调用');
    },
    custOption: 'cust',
    data() {
      return {
        message: 'goodbye',
        bar: 'def'
      }
    },
    methods: {
      barM() {
       alert('barM')
      },
      conflicting() {
        alert('组件的键值对')
      }
    }
  }
</script>

<style scoped>
  .aC {
    width: 100px;
    height: 100px;
    background: red;
  }
</style>

效果如下

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表