1.mixin.js文件定义
mixin.js文件定义
// mixin.js
export default {
data () {
return {
from: 'from mixin data'
}
},
mounted () {
console.log('from mixin mounted')
},
methods: {
handleInit () {
console.log('from mixin methods')
}
}
}
2.全局文件main.js引入mixin
全局文件main.js引入mixin
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import mixin from './mixin/index.js'
const app = createApp(App)
app.mixin(mixin)
app.mount('#app');
3.组件内使用mixin
1.模板内直接使用mixin
// 1.模板内直接使用mixin
<template>
<div>
<h3>mixin</h3>
<el-button @click="handleInit">mixin使用</el-button>
</div>
</template>
运行结果
2.组件方法调用mixin
// 组件方法调用mixin
<template>
<div>
<h3>mixin</h3>
<el-button @click="onClick">组件内方法调用mixin使用</el-button>
</div>
</template>
<script>
// getCurrentInstance获取当前组件实例
import { getCurrentInstance, onMounted } from "vue";
export default {
setup () {
const { proxy, ctx } = getCurrentInstance()
onMounted(() => {
console.log("组件内mounted");
})
const onClick = () => {
console.log('组件内方法调用mixin使用')
proxy.handleInit()
}
return {
onClick
}
}
}
</script>
运行结果
网友评论