mixin
将一些可复用的对象参数封装给mixin,将data,methods,computed,created,进行混合,
如果混合过程中,遇到同名属性,采用vue实例对象的或者组件对象中的,
如果具有相同的钩子函数(生命周期函数),那么两个函数会被放入数组中,均会被调用,(先调用mixin中的,再调用实例对象/组件对象中的)
如果具有相同的函数,调用vue实例对象中的函数
1.全局混入: 注:谨慎使用,因为每一个实例对象都会进行混入
Vue.mixin({ //可复用的对象或函数 data(){ return {} }, methods:{}, created(){} })实例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="../vue.js"></script> <script> window.onload=function(){ Vue.mixin({ data(){ return { num:10 } }, created(){ alert('mixin中的created') }, methods:{ handler(){ alert('这是mixin的handler') } } }) var app=new Vue({ el:'#app', data:{ str:'小仙女丫', num:2 }, methods:{ handler(){ alert('new vue函数') } }, created(){ alert('new Vue的created') }, components:{} }) } </script> </head> <body> <div id="app"> {{num}}--{{str}} <button v-on:click='handler'>花花</button> </div> </body> </html>局部混入:
var mixin={ data(){ }, methods:{} } new Vue({ el: data methods mixins:[mixin] })实例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="../vue.js"></script> <script> window.onload=function(){ var mixin={ data(){ return { num:10 } }, created(){ alert('这是mixin的alert') } } var app=new Vue({ el:'#app', data:{ num:99 }, methods:{}, mixins:[mixin], components:{ 'my-div':{ data(){ return { num:100 } }, methods:{}, mixins:[mixin], template:` <div> <p>{{num}}</p> </div> ` } }, }) } </script> </head> <body> <div id="app"> {{num}} <my-div></my-div> </div> </body> </html>