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')" alt=""> <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')" alt=""> <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>
