作用:减少重复
- directives的作用是减少DOM操作的重复
- mixins的作用是减少data、methods、 钩子的重复
收用场景
- 如果需要在每个组件上添加name和time
- 在created 、destroyed时,打出提示,并报出存活时间
- 如果有5个组件,请问要怎么做?
- 给每个组件添加data和钩子,共5次
- 或者使用mixins减少重复
与mixins的需求一样比mixins更抽象一点的封装
如果不想每次写mixins,可以使用Vue.extend,或者options.extends
const MyVue = Vue.extend({
data(){return{name:'',time:underfined}}
created(){
if(!this.name){console.error('no name!')}
this.time = new Date()
},
beforeDestroy(){
const duration = (new Date()) - this.time
console.log(`${this.name}存活时间${duration}`)
}
})