// mixin.js
export myMixin = { computed: { foo(): 'hi' } }
除了将其添加到 vue 之外,只需创建一个对象(并可能将其标记为导出)。
它只是一个对象。它里面有computed、data等特殊名称,但它只是一个对象。
// usage.vue
import { myMixin } from './path/to/myMixin.js'
console.log( myMixin.computed.foo ) // hi
export default {
mixins: [ myMixin ],
computed: { bar(): { this.foo } // hi
}
在上面的例子中,我没有使用全局 mixin,因为引用 vue docs
谨慎使用全局 mixins,因为它会影响创建的每个 Vue 实例,包括第三方组件。
现在,如果您真的需要一个全局 mixin,这就是它的用途,但请注意,要在 vue export default 之外使用 myMixin,您需要通过全局范围访问它,例如 window,或者像上面一样导入它。有关详细信息,请参阅以下查询:global functions in js。
我的偏好:
// in a file at /path/to/index.js
export { myMixin1 } from './myMixin1' // ...
// usage.vue
import { myMixin1, myMixin2 } from './path/to'
export default { mixins: [ ... ] }
或者在需要的地方,(因为 mixins 可以包含其他 mixins ;)虽然我发现在其他 JS 中使用它们比较困难
export myMixin1 = { ... }
export myMixin2 = {
mixins: [ myMixin1 ]
// ...
}
// usage.vue
import { myMixin2 } from 'path/to/myMixins'
export default {
mixins: [ myMixin2 ] // contains both 1 and 2
}
请注意,您也可以在 Vue 文件(单个文件组件)中声明,然后像 Javascript 一样从它们导入。
此外,您(显然)不需要导出它们 - 它们对于分离关注点已经很有用了。
// example.vue
<script>
export myMixin = { ... }
// all mixins can interact with each other
// because in the end, they will be parts of the same object
myToggle = { ... }
mySuperComplicatedBit = { ... }
// so B can call this.A
export default {
mixins: [
myMixin,
myToggle,
mySuperComplicatedBit
],
...
}
</script>
<template> ...
// other.vue or other.js
import { myMixin } from 'path/to/example.vue'
祝你好运