【发布时间】:2020-01-25 10:51:50
【问题描述】:
在 Vue 组件中注册函数的首选方法是什么。
我倾向于仅在组件中注册视图所需的方法(或需要直接组件数据访问)以及视图外部视图不需要的其他功能。
假设utilityFunction() 和utilityFunctionTwo() 当前仅在该组件内部使用。
这是一个例子:
<template>
<button @click="bar"></button>
<button @click="foo"></button>
<button @click="baz"></button>
</template>
<script>
export default {
name: "SampleComponent",
data() {
return {
someVariable: "ABC",
otherVariable: 123
}
},
methods: {
foo() {
//some logic
utilityFunction(this.someVariable);
//other logic
},
bar() {
//some logic
utilityFunction(this.someVariable);
utilityFunctionTwo(this.otherVariable);
//some other logic
},
baz() {
//some logic
utilityFunctionTwo(this.someVariable);
//some other logic
}
}
}
function utilityFunction(arg){
//do something
}
function utilityFunctionTwo(arg){
//do something
}
</script>
参数可能不同,实用程序函数可以是纯的并返回一些东西或改变参数。可能有很多不同的场景。但我希望你明白这一点。
另一种方法是将这些函数作为方法添加到您的组件中。 像这样:
<template>
<button @click="bar"></button>
<button @click="foo"></button>
<button @click="baz"></button>
</template>
<script>
export default {
name: "SampleComponent",
data() {
return {
someVariable: "ABC",
otherVariable: 123
}
},
methods: {
foo() {
//some logic
this.utilityFunction();
//other logic
},
bar() {
//some logic
this.utilityFunction();
this.utilityFunctionTwo(this.otherVariable);
//some other logic
},
baz() {
//some logic
this.utilityFunctionTwo(this.someVariable);
//some other logic
},
utilityFunction() {
//do something
console.log(this.someVariable)
//other stuff
},
utilityFunctionTwo(arg) {
//do something
}
}
}
</script>
在这种方法中,您有时不需要将参数传递给方法,因为它可以访问组件 data 对象。
由于原因,我稍微喜欢第一种方法:
- 我有模板使用的或组件所需的方法的简短列表(出于某种原因)。如果所有方法都放在那里,有时这个列表会变得很长。
- 如果函数将来可以在其他地方使用,我将能够轻松地将其添加到某个
.js文件中并将其导入其他组件中。 - 如果不需要,函数无权访问组件范围
- 它让我不用输入
this关键字 ;-) 如果在 lambda 中使用,有时可能会很有用。
我不确定这是否是一个意见问题,您是否可以纯粹根据您的个人喜好选择一种方法而不是另一种方法,或者它们是否是您应该选择一种方法而不是另一种方法的任何客观原因,例如(但不限于)被一种解决方案破坏的软件设计组件或原则的性能。
【问题讨论】:
-
如果我理解正确你的意思,你需要使用 mixins vuejs.org/v2/guide/mixins.html 。
-
不,不是这样的。
标签: javascript vue.js vue-component