Zyc*_*hoo 4 javascript vue.js vue-component
在 Vue 组件中注册函数的首选方法是什么。我倾向于仅在组件中注册视图所需的方法(或需要直接访问组件数据)和其他视图不需要的 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>
Run Code Online (Sandbox Code Playgroud)
参数可能不同,效用函数可以是纯函数并返回某些内容或改变参数。可以有很多不同的场景。但我希望你明白这一点。
另一种方法是将这些函数作为方法添加到您的组件中。像这样:
<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>
Run Code Online (Sandbox Code Playgroud)
在这种方法中,您有时不需要将参数传递给方法,因为它可以访问组件data
对象。
由于原因,我稍微更喜欢第一种方法:
.js
文件并将其导入其他组件。this
关键字 ;-) 如果在 lambda 中使用,有时可能会很有用。我不确定这是否是一个意见问题,您可以纯粹根据您的个人喜好选择一种方法而不是另一种方法,或者它们是否有任何客观原因您应该选择一种方法而不是另一种方法,例如(但不限于)组件的性能或被一种解决方案破坏的软件设计原则。
不同之处在于utilityFunction
和utilityFunctionTwo
辅助函数是不可测试的。它们不能直接访问。他们不能被嘲笑,即使他们是:
export function utilityFunction(arg){
//do something
}
export function utilityFunctionTwo(arg){
//do something
}
Run Code Online (Sandbox Code Playgroud)
正如这里所解释的,由于模块的工作方式,只有从一个模块导出并在另一个模块中使用时,才有可能监视或模拟一个函数。
为了完全可测试或可重复使用的,utilityFunction
并且utilityFunctionTwo
应该被移动到另一个模块。
由于它们被组件私有使用并且不会被重用,一个合理的替代方法是将它们设为私有方法,这可以用下划线表示法指定:
methods: {
...
_utilityFunction() {
//do something
},
_utilityFunctionTwo(arg) {
//do something
}
}
Run Code Online (Sandbox Code Playgroud)
一个缺点是,如果不使用方法,它们不能作为死代码自动删除,但常规函数可以。