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>