// 你可以定义多个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‘ } } }
<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>
原文:https://www.cnblogs.com/steamed-twisted-roll/p/10906091.html