vue混入的用法

定义minxin

//minxin.js

var myMixin = {
  data: function () {
    return {
      message: 'hello',
      foo: 'abc'
    }
  },
  created: function () {
    console.log('混入对象的钩子被调用')

  },
  methods: {
    foo1: function () {
      console.log('foo1');

    },
    conflicting: function () {
      console.log('from mixin');
    }
  }
}

export default myMixin;

页面使用

<template>
  <div class="mixin" v-wechat-title="$route.meta.title"></div>
</template>

<script>
import myMixin from "./minxin.js";
export default {
  name: "mixin",
  mixins: [myMixin], //引入mixins
  data() {
    return {
      message: "goodbye",
      bar: "def"
    };
  },
  components: {},
  created() {
    console.log("组件钩子被调用");

    // => "混入对象的钩子被调用"
    // => "组件钩子被调用"
    // ------表明混入里的钩子函数先与组件的钩子函数先调用

    // ------如果组件里有就用组件里的   没有就用混入里的
    console.log(this.$data); // => { message: "goodbye", foo: "abc", bar: "def" }
  },

  watch: {},
  //值为对象的选项,例如 methods、components 和 directives,将被合并为同一个对象。两个对象键名冲突时,取组件对象的键值对。
  mounted() {
    this.foo1(); // => "foo1"
    this.bar1(); // => "bar1"
    this.conflicting(); // => "from self"
  },

  methods: {
    bar1: function() {
      console.log("bar1");
    },
    conflicting: function() {
      console.log("from self");
    }
  },

  computed: {}
};
</script>


<style  scoped lang="scss">
</style>

全局混入

//mian.js


Vue.mixin('混入的js');

自定义属性

//自定义一个属性
new Vue({
  data: function() {
    return {
      
    };
  },
  created: function () {

  },
  mounted() {},
  methods: {
  },
  myOption: '自定义属性!'
})


//针对自定义属性做操作(使用混入)
Vue.mixin({
  myOption:'minxi里自定义参数',
  created: function () {
    var myOption = this.$options.myOption
    if (myOption) {
      console.log(myOption)
    }
  }
})

自定义选项合并策略

main.js

//1自定义选项将使用默认策略,即简单地覆盖已有值。如果想让自定义选项以自定义逻辑合并,可以向 Vue.config.optionMergeStrategies 添加一个函数:

Vue.config.optionMergeStrategies.myOption = function (toVal, fromVal) {
  // 返回合并后的值
}

//2对于多数值为对象的选项,可以使用与 methods 相同的合并策略:

var strategies = Vue.config.optionMergeStrategies
strategies.myOption = strategies.methods

//3  可以在 Vuex 1.x 的混入策略里找到一个更高级的例子:

const merge = Vue.config.optionMergeStrategies.computed
Vue.config.optionMergeStrategies.vuex = function (toVal, fromVal) {
  if (!toVal) return fromVal
  if (!fromVal) return toVal
  return {
    getters: merge(toVal.getters, fromVal.getters),
    state: merge(toVal.state, fromVal.state),
    actions: merge(toVal.actions, fromVal.actions)
  }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值