Vue之mixin混合
mixin(混入)
1. 功能:可以把多个组件共用的配置提取成一个混入对象
2. 使用方式:
第一步定义混合:
```
{
data(){....},
methods:{....}
....
}
```
第二步使用混入:
全局混入:```Vue.mixin(xxx)```
局部混入:```mixins:['xxx'] ```
代码结构:

School.vue
<template> <div> <h2 @click="showName">学校名称:{{name}}</h2> <h2>学校地址:{{address}}</h2> </div> </template> <script> //引入一个hunhe 局部混合 // import {hunhe,hunhe2} from '../mixin' export default { name:'School', data() { return { name:'School', address:'北京', x:666 } }, // mixins:[hunhe,hunhe2],// 局部混合使用 } </script>
Student.vue
<template> <div> <h2 @click="showName">学生姓名:{{name}}</h2> <h2>学生性别:{{sex}}</h2> </div> </template> <script> // import {hunhe,hunhe2} from '../mixin' export default { name:'Student', data() { return { name:'张三', sex:'男' } }, // mixins:[hunhe,hunhe2] } </script>
App.vue
<template> <div> <School/> <hr> <Student/> </div> </template> <script> import School from './components/School' import Student from './components/Student' export default { name:'App', components:{School,Student} } </script>
mixin.js
export const hunhe = {
methods: {
showName(){
alert(this.name)
}
},
mounted() {
console.log('你好啊!')
},
}
export const hunhe2 = {
data() {
return {
x:100,
y:200
}
},
}
main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//关闭Vue的生产提示
Vue.config.productionTip = false
// 混合全局引用
import {hunhe,hunhe2} from './mixin'
Vue.mixin(hunhe)
Vue.mixin(hunhe2)
//创建vm
new Vue({
el:'#app',
render: h => h(App)
})
浙公网安备 33010602011771号