mixin混合

student.vue

<template>
    <div class="student">
            <h2>{{name}}</h2>
            <h2>{{age}}</h2>
            <button @click="showName">点我显示名字</button>
        </div>
</template>
    
<script>
// 局部引入
import {hunhe,hunhe2} from '../mixin.js' export default{ name:'Student', /*data() { return{ name:'张三', age:18 } },*/ mixins:[hunhe,hunhe2] } </script> <style> </style>

school.vue

<template>
    <div class="school">
            <h2>{{name}}</h2>
            <h2>{{Add}}</h2>
            <button @click="showName">点我显示名字</button>
        </div>
</template>
    
<script>
    import {hunhe} from '../mixin.js'
        export default{
            name:'School',
            data() {
                return{
                    name:'老年大学',
                    Add:'加利福尼亚'
                }
            },
            mixins:[hunhe]
        }
</script>
    
<style>
</style>

mixin.js

export const hunhe = {
    methods:{
        showName(){
            alert(this.name)
        }
    }
}
export const hunhe2 = {
    data(){
        return{
            name:"大王",
            age:18
        }
    }
}

main.js

import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
//全局引入  此时单独的组建不需再次引入mixin.js,使用mixins
import {hunhe,hunhe2} from './mixin.js'
Vue.mixin(hunhe)
Vue.mixin(hunhe2)

new Vue({
  render: h => h(App),
}).$mount('#app')

 

上一篇:Mixin实现组件功能的复用 、全局配置Mixin


下一篇:685 vue3 mixin,extends