Vue的混入mixins

混入 (mixin) 提供了一种非常灵活的方式,来分发 Vue 组件中的可复用功能。一个混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项。

我们先看混入的一个可复用的特点

mixins文件

 1 export const MixIns={
 2     data(){
 3        return {
 4         a:100
 5        }
 6     },
 7     methods:{
 8         add(){
 9             this.a++
10         }
11     }
12 }

app.vue组件

 1 <template>
 2   <div>
 3     {{a}}
 4     <button @click="add">加一</button>
 5     <Child>
 6     
 7     </Child>
 8   </div>
 9 </template>
10 
11 <script>
12 import {MixIns} from "./mixins.js"
13 import Child from "./components/Child.vue"
14   export default {
15     mixins:[MixIns],
16     components:{
17       Child
18     }
19   }
20 </script>
21 
22 <style lang="scss" scoped>
23 
24 </style>

child.vue组件

 1 <template>
 2     <div>
 3        子组件 {{a}}
 4     <button @click="add">加一</button>
 5     </div>
 6 </template>
 7 
 8 <script>
 9 import {MixIns} from "../mixins.js"
10     export default {
11         mixins:[MixIns]
12     }
13 </script>
14 
15 <style lang="scss" scoped>
16 
17 </style>

和components类似的是,混入也需要注册,mixins:[],数组内部是引入的对应的可复用的功能文件

我们给子组件Child也进行了mixins混入

此时我们发现点击父组件和子组件,同时设置add,然后让a加1,但是并没有操作同一个a,而是互相隔离

 

 

 

思考一个问题,如果App组件中内部也设置了add方法,此时会听谁的?

 1 <script>
 2   import {MixIns} from './mixins.js'
 3   
 4   export default {
 5     mixins:[MixIns],
 6     methods:{
 7       add() {
 8         this.a += 3
 9       }
10     }
11     
12   }
13 </script>

此时浏览器会按步长为3的加

 

 

 此时我们添加一个created函数,发现输出为methods中的方法

1  created(){        //生命周期函数
2       console.log(this.add)
3     }

 

通过上面的案例我们知道,如果组件内部的方法和mixins中有冲突了,组件内部的方法权重高

先预习一下后面会遇到的生命周期函数的问题

如果此时我们在mixins文件中加了created,会分别依次执行,不会进行覆盖

mixins文件的代码

 1 export const MixIns={
 2     data(){
 3        return {
 4         a:100
 5        }
 6     },
 7     methods:{
 8         add(){
 9             this.a++
10         }
11     },
12     created(){
13         this.a++
14         console.log(this.a)   
15         console.log("我是混入的生命周期函数")
16       }
17 }

app.vue文件的代码

 1 <template>
 2   <div>
 3     {{a}}
 4     <button @click="add">加一</button>
 5   </div>
 6 </template>
 7 
 8 <script>
 9 import {MixIns} from "./mixins.js"
10 // import Child from "./components/Child.vue"
11   export default {
12     mixins:[MixIns],
13     components:{
14       // Child
15     },
16     methods:{
17       add(){
18         this.a+=3
19         console.log(this.a)
20       }
21     },
22     created(){
23       this.a++
24   console.log(this.a)
25       console.log("我是app.vue的生命周期函数")
26     }
27   }
28 </script>
29 
30 <style lang="scss" scoped>
31 
32 </style>

 

 
posted @ 2021-09-16 15:44  keyeking  阅读(102)  评论(0编辑  收藏  举报