<!DOCTYPE html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>hello world</title> <script src="https://unpkg.com/vue@next"></script> </head> <body> <div id="root"></div> </body> <script> const MyMixin = { data() { return { number: 2, count: 3 } } } const app = Vue.createApp({ data() { return { number: 1 } }, mixins: [MyMixin], template: ` <div>number:{ <!-- -->{number}}</div> <div>count:{ <!-- -->{count}}</div> ` }); app.mount('#root'); </script> </html>
mixin 混入可以在组件内部缺少数据时,使用mixin内的数据代替。
上述代码中,count 使用了 mixin 内的数据,由于内部 number 已经被定义,vue 优先使用内部的数据,再使用 mixin 的数据。
<!DOCTYPE html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>hello world</title> <script src="https://cdn.staticfile.org/vue/3.0.5/vue.global.js"></script> </head> <body> <div id="root"></div> </body> <script> const MyMixin = { created(){ console.log('mixin created') } } const app = Vue.createApp({ mixins:[MyMixin], created(){ console.log('app created') } }); app.mount('#root'); </script> </html>
效果如下:
<!DOCTYPE html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>hello world</title> <script src="https://cdn.staticfile.org/vue/3.0.5/vue.global.js"></script> </head> <body> <div id="root"></div> </body> <script> const MyMixin = { data(){ return{ number:123 } } } const app = Vue.createApp({ mixins:[MyMixin], template:`<app/>` }); app.component("app",{ template:"<div>number:{ <!-- -->{number}}</div>" }) app.mount('#root'); </script> </html>
使用 mixins:[myMixin] 是局部载入mixin的方式,子组件不能获得 mixins 的值
运行结果如下:
<!DOCTYPE html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>hello world</title> <script src="https://cdn.staticfile.org/vue/3.0.5/vue.global.js"></script> </head> <body> <div id="root"></div> </body> <script> const app = Vue.createApp({ template: `<app/>` }); app.mixin({ data() { return { number: 123 } } }) app.component("app", { template: "<div>number:{ <!-- -->{number}}</div>" }) app.mount('#root'); </script> </html>
使用 app.mixin 挂载就是全局,组件可以自由使用。
效果如下:
<!DOCTYPE html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>hello world</title> <script src="https://cdn.staticfile.org/vue/3.0.5/vue.global.js"></script> </head> <body> <div id="root"></div> </body> <script> const myMixin = { value: 1 } const app = Vue.createApp({ mixins: [myMixin], value: 25, template: `<div>{ <!-- -->{this.$options.value}}</div>` }); app.mount('#root'); </script> </html>
vue 中,自定义属性就是直接写到vue下的属性,使用 this.$options.value 即可访问。
结果如下:
组件 data,methods优先级高于 mixin data,methods 优先级
生命周期函数,先执行 mixin 里边的,再执行组件里边的
自定义的属性,组件中的优先级高于 mixin 属性的优先级。