Vue.js VueJS功能组件(SFC):如何封装代码?
我在VueJS中编写了一个简单的模板替换组件作为单个文件组件。它没有很多特性:只有一个道具,而且我还制作了一个计算属性来封装在模板中使用之前对该道具所做的一些复杂转换。它看起来如下所示:Vue.js VueJS功能组件(SFC):如何封装代码?,vue.js,vuejs2,vue-component,Vue.js,Vuejs2,Vue Component,我在VueJS中编写了一个简单的模板替换组件作为单个文件组件。它没有很多特性:只有一个道具,而且我还制作了一个计算属性来封装在模板中使用之前对该道具所做的一些复杂转换。它看起来如下所示: <template> ...some-html-here... <a :href="myHref">...</a> ... </template> <script> export default { name: 'MyCo
<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>
…这里有一些html。。。
...
导出默认值{
名称:“MyComponent”,
道具:{
href:{type:String,必需:true},
},
计算:{
myHref(){
让result=this.href;
//几行复杂的逻辑进行替换等等
// ...
返回结果;
}
}
};
现在我认为这应该是一个功能组件,因为它没有状态,没有数据,没有反应性,所以在整个实例周围乱跑是浪费的
我只需将“functional”属性添加到我的
中,就可以使此功能正常。当然,在功能组件中,没有诸如计算属性、方法之类的东西。所以我的问题是:我可以把我的几行复杂的逻辑放在哪里?我不想把它直接嵌入到我的模板中,特别是因为它被用于多个地方。那么,我在哪里可以放置代码来转换我的输入道具,并使它们准备好在我的模板中使用呢
很好的问题。我试图找到相同的答案,但我最终得出以下结论,我不知道这是否是一个好方法
html部分:
<template functional>
<div>
<button @click="props.methods.firstMethod">Console Something</button>
<button @click="props.methods.secondMethod">Alert Something</button>
</div>
</template>
<script>
export default {
props: {
methods: {
type: Object,
default() {
return {
firstMethod() {
console.log('You clicked me')
},
secondMethod() {
alert('You clicked me')
}
}
}
}
}
}
</script>
安慰
警觉
js部分:
<template functional>
<div>
<button @click="props.methods.firstMethod">Console Something</button>
<button @click="props.methods.secondMethod">Alert Something</button>
</div>
</template>
<script>
export default {
props: {
methods: {
type: Object,
default() {
return {
firstMethod() {
console.log('You clicked me')
},
secondMethod() {
alert('You clicked me')
}
}
}
}
}
}
</script>
导出默认值{
道具:{
方法:{
类型:对象,
默认值(){
返回{
第一种方法(){
console.log('您单击了我')
},
第二种方法(){
警报('您单击了我')
}
}
}
}
}
}
一定要读到
注意:请注意使用这种方法,因为功能组件是无状态的(无反应数据)和无实例的(无此上下文)。我在这些场景中使用过渲染函数。如果您不喜欢使用函数语法,也可以使用jsx.Good point——这当然可以通过切换到渲染函数来实现。我真的在寻找在标记中保留模板优点的方法。