如何重构需要使用完全相同方法的两个组件?在那里定义父组件和相同的方法?
Vue.component("one", {
method: {
functionA:
}
});
Vue.component("two", {
method: {
functionA
}
});
答案 0 :(得分:6)
您始终可以创建mixin:
var mixin = {
methods: {
consoleMessage() {
console.log('hello from mixin!')
}
},
created() {
this.consoleMessage()
}
}
Vue.component('one', {
mixins: [mixin],
template: `<div>one</div>`
})
Vue.component('two', {
mixins: [mixin],
template: `<div>two</div>`
})
new Vue({
el: '#app'
})
&#13;
<script src="https://unpkg.com/vue"></script>
<div id="app">
<one></one>
<two></two>
</div>
&#13;
答案 1 :(得分:1)
没有人认为mixin可以在这里使用,但这也可以用普通的javascript来解决。
function consoleMessage(){
console.log("hello from regular old javascript!")
}
Vue.component('one', {
template: `<div>one</div>`,
methods: { consoleMessage },
created() { this.consoleMessage() }
})
Vue.component('two', {
template: `<div>two</div>`,
methods: { consoleMessage },
created() { this.consoleMessage() }
})
new Vue({
el: '#app'
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<one></one>
<two></two>
</div>
如果使用现代模块,则可以定义要在模块中共享的功能,并将其导入两个组件。
<强> shared.js 强>
export function consoleMessage(){
console.log("hello from regular javascript!")
}
<强> componentOne.js 强>
import { consoleMessage } from "./shared"
export default {
template: `<div>one</div>`,
methods: { consoleMessage },
created() { this.consoleMessage() }
}
<强> componentTwo.js 强>
import { consoleMessage } from "./shared"
export default {
template: `<div>two</div>`,
methods: { consoleMessage },
created() { this.consoleMessage() }
}