首页 > 其他 > 详细

vue + mixin混入对象使用

时间:2019-05-22 15:44:21      阅读:100      评论:0      收藏:0      [点我收藏+]
vue提供的混入对象mixin,类似于一个公共的组件,其他任何组件都可以使用它.我更经常的是把它当成一个公共方法来使用
在项目中有些多次使用的data数据,method方法,或者自定义的vue指令都可以放到mixin中,引入到各自的组件就可以使用,非常方便.这里写一下局部的混入组件使用,不建议在项目中使用全局混入..
 
首先写一个mixin.js文件,可以放在common公共组件中

src/components/common/mixin.js
// 你可以定义多个mixin对象,在里面就和普通的组件一样,定义data,method
export const mymixin = {
  data() {
    return {
      msg: ‘hello word, from mymixin‘
    }
  },

  // 自定义指令
  directives: {
    focus: {
      inserted: function (el) {
        el.focus()
      }
    }
  },

  methods: {
    // 处理图片方法
    handleImg (url) {
      if (url && url.indexOf(‘.jpg‘) > -1) {
        return url
      } else return ‘https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1840587501,62677872&fm=27&gp=0.jpg‘
    }
  }
}

 

在组件中引入使用,在混入对象中定义的data,method会被合并到当前组件中,可以直接使用混入对象里的data
<template>
  <div>
    mixintest
    <h2>{{msg}}</h2>
    调用mixin方法:<img :src="handleImg(‘http://pic.58pic.com/58pic/15/17/01/47U58PICVQJ_1024.png‘)" >
    <h4>自动获取焦点</h4>
    <input type="text" v-focus>
  </div>
</template>
<script>
  import {mymixin} from ‘./common/mixin‘

  export default {
    name: ‘mymixin‘,
    mixins: [mymixin],
    components: {

    },
    data() {
      return {

      }
    },
    methods: {
      
    }

  }
</script>
<style scoped>

</style>

 

使用效果:

技术分享图片

 

如果引入组件定义的数据和混入对象的名称重复,组件的数据会覆盖混入对象的属性
 
<template>
  <div>
    mixintest
    <h2>{{msg}}</h2>
    调用mixin方法:<img :src="handleImg(‘http://pic.58pic.com/58pic/15/17/01/47U58PICVQJ_1024.jpeg‘)" >
    <h4>自动获取焦点</h4>
    <input type="text" v-focus>
  </div>
</template>
<script>
  import {mymixin} from ‘./common/mixin‘

  export default {
    name: ‘mymixin‘,
    mixins: [mymixin],
    components: {

    },
    data() {
      return {
        msg: ‘自己组件的数据‘
      }
    },
    methods: {
      
    }

  }
</script>
<style scoped>

</style>

 

技术分享图片

vue + mixin混入对象使用

原文:https://www.cnblogs.com/steamed-twisted-roll/p/10906091.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!