一、mixin混入
mixin
即合並公共方法: 可以設置通用的方法或者變量
外部mixin
如下:
全局mixin
:Vue.mixin = ({})
export const m1 = { data(){ return { nickname: '張三' // data的變量會被單頁里定義的給覆蓋 } }, mounted(){ console.log('123') // 但是mounted是不會覆蓋的,這里會執行 }, methods: { sayHello() { console.log('hello') } } } new Vue({ el: '#app', mixins: [m1], data() { return { nickname: '李四', // 若在本vue中也定義了同名變量,則這個值會覆蓋mixins定義的 age: 20 } }, mounted(){ console.log('456') // 但是mounted是不會覆蓋的,這里也會執行 this.sayHello(); } })
{{nickname}}-{{age}}
若在單頁里不定義nickname
也能拿到nickname
,因為minxins
混入了原先已經定義好的
二、Vue 自定義插件
var my_plugin = { install (Vue, options) { // 這個必須 // 混入 Vue.mixin({ data(){ return { nickname: '張三' // data的變量會被單頁里定義的給覆蓋 } }, mounted(){ console.log('123') // 但是mounted是不會覆蓋的,這里會執行 }, methods: { sayHello() { console.log('hello') } } }) // 自定義組件 Vue.component("sb",{ template: "<h1>simba組件</h1>" }) // 自定義指令 Vue.directive("focus", { inserted(el) { el.focus() } }) // 擴展屬性 Vue.prototype.$log = console.log if (options && options.debug){ } } }
插件寫好后 使用Vue.use(my_plugin)
安裝下即可使用
在vue文件中調用
<sb/> // 使用組件 <input type="text" v-focus> // 使用指令 $log('111'); // 使用屬性 同上還能使用混入的方法
若這么寫
Vue.use(my_plugin,{ debug: true})
那么上面的插件代碼options就能取到值debug: true
作者:Do_Du
鏈接:https://www.jianshu.com/p/dac7d15ed8d3
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。