1.简介
1.1 官方简介
混入 (mixin) 提供了一种非常灵活的方式,来分发 Vue 组件中的可复用功能。一个混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项。
1.2个人理解
程序的本质就是辅助人来做事情,能有代码实现的,坚决不手动实现,例如,假如每个页面都用到的一个方法,每个页面都复制一份使用,极大的浪费时间精力,mixins 就是为了解决这个问题(不仅仅是方法)。
2. 使用
代码实例如下 混入有两种 全局 和 局部
// mixins.js
export default {
components: {
},
created(){
},
methods:{
// 公用的方法
handleAdd(){
this.$store.dispatch('home/addAge')
},
aaa(){
console.log('aaa')
},
bbb(){
console.log('bbb')
},
ccc(){
console.log('ccc')
},
}
}
// main.js 引入
import Vue from 'vue'
import App from './App.vue'
import store from './store'
import mixin from './mixin'
Vue.config.productionTip = false
// 混入
Vue.mixin(mixin)
new Vue({
store,
render: h => h(App)
}).$mount('#app')
2.1 验证是否成功
直接在页面上调用混入的方法, 能出结果就是成功了
<template>
<div id="app">
<h1>{{name}}</h1>
<h1>{{age}}</h1>
<button @click="handleAdd">点击</button>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
name: 'App',
components: {
},
created(){
this.aaa() // aaa
},
methods:{
},
computed:{
...mapState('home', ['name', 'age'])
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
2.2 局部使用
<template>
<div id="app">
<h1>{{name}}</h1>
<h1>{{age}}</h1>
<button @click="handleAdd">点击</button>
</div>
</template>
<script>
import { mapState } from 'vuex'
import mixin from './mixin'
export default {
name: 'App',
mixins:[mixin], // 混入
components: {
},
created(){
this.aaa()
},
methods:{
handleAdd(){
this.$store.dispatch('home/addAge')
}
},
computed:{
...mapState('home', ['name', 'age'])
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
欢迎点赞、评论、关注