How do I extend another VueJS component in a singl

2020-02-23 06:35发布

I am using vue-loader (http://vuejs.github.io/vue-loader/start/spec.html) to construct my *.vue single-file components, but I am having trouble with the process from extending a single-file component from another.

If one component follows the spec to export default { [component "Foo" definition] }, I would think it is just a matter of importing this component (as I would with any child component) and then export default Foo.extend({ [extended component definition] })

Unfortunately this does not work. Can anyone please offer advice?

4条回答
ら.Afraid
2楼-- · 2020-02-23 06:44

Another possibility is the extends option:

import Foo from './Foo'

export default { extends: Foo }
查看更多
Juvenile、少年°
3楼-- · 2020-02-23 06:47

The proper way to do this would be to use mixins: http://vuejs.org/guide/mixins.html

Think of mixins as abstract components, which you can extend. So you could create a mixin with any functionality you wanted to have in both, and then just apply it to each of your components.

查看更多
劳资没心,怎么记你
4楼-- · 2020-02-23 06:53

I'd avoid the "extends" feature of Vue, simply because it is a poorly named method of Vue. It doesn't really extend anything, not in the case of inheritance. What it does is exactly what the mixin does, it merges the two components together. It has nothing to do with the template code, which isn't extensible either. The "extend" Vue method should have been called "merge".

At any rate, Vue must work with the hierarchy of the DOM and thus it composes to the DOM. That same thinking should rule your SFC building. Use component mixins for base behavior and add the mixins to your components as you need that behavior, while composing together the smallest common parts into bigger parts, all at the same time keeping your template code to a minimum. You should think "thin views, think models" while composing your SFCs. :)

查看更多
叼着烟拽天下
5楼-- · 2020-02-23 07:04

After some testing, the simple solution was to be sure to export a Vue.extend() object rather than a plain object for any component being extended.

In my case, the base component:

import Vue from 'vue'

export default Vue.extend({ [component "Foo" definition] })

and the extended component:

import Foo from './Foo'

export default Foo.extend({ [extended component definition] })
查看更多
登录 后发表回答