组件就是在复用代码,如果组件里面有许多配置是相同的可以借助混合去复用
1. minxin.js
//组件就是在复用代码,如果组件里面有许多配置是相同的可以借助混合去复用 export const hunhe={ methods:{ showName(){ alert(this.name); } }, //混合中的生命钩子函数和组件中的钩子函数都会执行,但是混合中的先执行 mounted() { console.log('混合里面的mounted') }, }export const hunhe2={ data(){ return { x:100, y:200 } }, } 2. Student.vue <template> <div class="demo"> <h2 @click="showName">学生姓名{{name}}</h2> <h2>学生性别{{sex}}</h2> </div> </template>
<script>
import {hunhe} from '../mixin' import {hunhe2} from '../mixin' export default { name:"Student", data() { return { name:"张三", sex:'男' }; },
// methods: { // showName(){ // alert(this.name); // } // }, mixins:[hunhe,hunhe2], mounted(){ console.log('组件中的mounted'); } } </script> 3. School.vue <template> <!-- 组件的介绍 --> <div class="school">
<h2 @click="showName">学校名称{{name}}</h2> <h2>学校地址{{address}}</h2>
</div> </template>
<script>
import {hunhe} from '../mixin' import {hunhe2} from '../mixin' hunhe2 export default { name:"School", data() { return { name: "洛阳理工", address: "洛阳", x:666 }; },
// methods: { // showName() { // alert(this.schoolName); // }, // }, mixins:[hunhe,hunhe2] }
</script>
<style scoped> /* 组件的样式 */ .school{ background-color:orange; }
</style> 4. App.vue <template> <div> <Student/> <School/> </div> </template>
<script> //引入student组件 import Student from './components/Student.vue' import School from './components/School.vue' import {hunhe,hunhe2} from './mixin' //全局混合 Vue.mixin(hunhe) Vue.mixin(hunhe2) export default { name: 'App', components: { Student, School, }, data(){ return { msg:"欢迎学习vue" } },
methods:{ showDOM(){ } } } </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> 标签:hunhe2,vue,name,--,mixin,import,hunhe From: https://www.cnblogs.com/satisfysmy/p/17574956.html