- 创建一个混入文件(例如 mixin.js)
// mixin.js
export const myMixin = {
methods: {
sharedMethod() {
console.log('This is a shared method from mixin');
},
anotherSharedMethod() {
console.log('This is another shared method from mixin');
}
}
}
- 导入混入
<template>
<div>
<!-- 可以直接使用-->
<button @click="sharedMethod">Use sharedMethod from Mixin</button>
<button @click="anotherSharedMethod">Use anotherSharedMethod from Mixin</button>
</div>
</template>
<script>
import { myMixin } from './myMixin.js';
export default {
name: 'MyComponent',
mixins: [myMixin],
data(){
return {}
},
...
}
</script>