我用VueJS编写了一个简单的模板替换组件,作为一个单一文件组件。它没有很多特性:只有一个支柱,我还做了一个计算属性来封装一些棘手的转换,这些转换是在模板中使用之前完成的。它看起来如下所示:
<template>
...some-html-here...
<a :href="myHref">...</a>
...
</template>
<script>
export default {
name: 'MyComponent',
props: {
href: { type: String, required: true },
},
computed: {
myHref() {
let result = this.href;
// several lines of complicated logic making substitutions and stuff
// ...
return result;
}
}
};
</script>现在,我认为这应该是一个功能组件,因为它没有状态,没有数据,没有反应性,因此在整个实例中乱转是浪费的。
我可以通过向我的<template>添加'functional‘属性来实现这个功能。当然,在功能组件中,不存在计算属性或方法之类的东西。所以我的问题是:我可以把我的几行复杂的逻辑放哪里?我不想将它直接嵌入到我的模板中,特别是因为它在多个地方使用。那么,我可以在哪里放置代码来转换我的输入道具并使它们可以在我的模板中使用?
发布于 2018-07-28 08:41:01
很棒的问题,我试图找到同样的答案,最后我得到了以下的答案,但我不知道这是否是一个好方法。
"html“部分:
<template functional>
<div>
<button @click="props.methods.firstMethod">Console Something</button>
<button @click="props.methods.secondMethod">Alert Something</button>
</div>
</template>"js“部分:
<script>
export default {
props: {
methods: {
type: Object,
default() {
return {
firstMethod() {
console.log('You clicked me')
},
secondMethod() {
alert('You clicked me')
}
}
}
}
}
}
</script>一定要阅读关于文档中的功能组件的文章
注意:使用这种方法时,需要注意,因为功能组件是无状态的(没有反应数据)和无实例的(没有此上下文)。
https://stackoverflow.com/questions/50682288
复制相似问题