Vue的mixin属性
功能: 可以把多个组件共用的配置提取成一个混入对象
1. mixin使用步骤
- 定义混合,例如:
js
{
data(){....}
methods: {....}
....
}
- 使用混入,例如:
- 全局混入:
Vue.mixin(xxxx)
- 局部混入:
mixins: ['xxx']
vue
<template>
<div>
<img alt="Vue logo" src="./assets/logo.png">
<School></School>
<Student></Student>
</div>
</template>
<script>
import School from "@/components/School.vue";
import Student from "@/components/Student.vue";
export default {
name: 'App',
components: {
School, Student
},
}
</script>
js
export const showName = {
methods: {
showName() {
alert(this.name)
}
}
}
export const myData = {
methods: {
showName() {
alert(this.name)
}
}
}
vue
<template>
<div class="hello">
<h2>{{ msg }}</h2>
<h2>学校名字:{{ name }}</h2>
<h2>学校地址: {{ schoolAddress }}</h2>
<button @click="showName">弹窗</button>
</div>
</template>
<script>
// 局部引入公共option的配置项mixin代码
import {showName} from '@/mixins.js'
export default {
name: 'School',
data() {
return {
msg: '欢迎大家!!',
schoolAddress: '四川',
name:'湘雅医学院'
}
},
mixins: [showName]
}
</script>
vue
<template>
<div class="hello">
<h2>{{ msg }}</h2>
<h2>名字:{{ name }}</h2>
<h2>年龄 {{ age }}</h2>
<button @click="showName">弹窗</button>
</div>
</template>
<script>
// 局部引入公共option的配置项mixin代码
import {showName} from '@/mixins.js'
export default {
name: 'Student',
data() {
return {
msg: '欢迎大家!!',
name: '张三',
age: 18
}
},
mixins: [showName]
}
</script>
js
// 引入vue
import Vue from 'vue'
// 引入App组件,它是所有组件的父组件
import App from './App.vue'
// 关闭vue的生产提示
Vue.config.productionTip = false
import { myData } from './mixins'
// 全局引入配置项
Vue.mixin(myData)
// 创建vm实例对象
new Vue({
// 将App组件放到容器中
render: q => q(App)
}).$mount('#app')
2. 如果mixin中有和子组件中相同的配置项,怎么样?
如果冲突了, 优先本地的属性