踩坑日记:mixin引用时单个混入对象也要用 {hunhe} 否则会引用失败。
1.src目录中创建mixin文件夹,文件夹内自定义js文件
2.js文件格式:export const一个对象,对象中和.vue文件的Option一样,可以有生命周期、data、methods等
export const hunhe = {
methods: {
showName(){
alert(this.name)
}
},
mounted() {
console.log('你好啊!')
},
}
export const hunhe2 = {
data() {
return {
x:100,
y:200
}
},
}
3.引用mixin
全局引用:
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
import {hunhe,hunhe2} from './mixin'
//关闭Vue的生产提示
Vue.config.productionTip = false
Vue.mixin(hunhe)
Vue.mixin(hunhe2)
//创建vm
new Vue({
el:'#app',
render: h => h(App)
})
局部引用:
<template>
<div>
<h2>x:{{x}}</h2>
</div>
</template>
<script>
//引入一个hunhe
// import {hunhe,hunhe2} from '../mixin'
export default {
name:'School',
data() {
return {
x:666
}
},
//使用mixin
// mixins:[hunhe,hunhe2],
}
</script>
4.mixin的特点
方法和参数在各组件中不共享
值为对象的选项,如methods,components等,选项会被合并,键冲突的组件会覆盖混入对象的
值为函数的选项,如created,mounted等,就会被合并调用,混合对象里的钩子函数在组件里的钩子函数之前调用
结语:mixin可以定义共用的变量,在每个组件中使用,引入组件中之后,各个变量是相互独立的,值的修改在组件中不会相互影响。