【发布时间】:2021-05-05 14:12:54
【问题描述】:
有Base.vue
<template><div>{{ name }}</div></template>
<script>
export default {
data() {
return {name: 'Example Component'};
}
};
</script>
还有Extended.vue:
<script>
import Base from './Base.vue';
export default {
extends: Base,
data() {
return {name: 'Extended Example Component'};
}
};
</script>
是否可以从基数重用data 而不是硬编码Extended Example Component?来自 OOP 的某种super?寻找涉及 mount、methods、computed 等内容的通用解决方案。
更新
在使用 OOP 时,我们使用这种方法(Python 示例):
class Base:
def __init__(self):
self.name = 'Example Component'
class Extended(Base):
def __init__(self):
super().__init__()
self.name = f'Extended {self.name}'
这样我们就可以重用self.name 字段。
【问题讨论】:
-
请澄清您的期望。 而不是硬编码扩展示例组件 - 但它是硬编码的,因为它应该与 Base 不同,不是吗?
extends和mixins合并数据和其他选项,这就是他们的目的 -
@EstusFlask 所以你的意思是在这个用例中扩展不是最好的选择?那么也许有任何替代方法建议?
-
如果不覆盖child中的“name”,那么访问“name”会得到父值,即“Example Component”,这就是我们所期望的。所以我看不出你在问什么。
-
@jaudo 这是一个确切的问题:如何在
Extended组件中引用Base组件的name值?请注意name是data的一个字段,所以我更一般地询问data。我也对mounted、computed、methods等其他功能感兴趣。 -
使用 this.name 将访问 Base 值。除非它在扩展中被覆盖。在这种情况下,基本值是不可达到的(就像我所知道的所有 OOP 语言一样)
标签: javascript vue.js vuejs2 module vue-component