typescript - 将计算的 setter 编写为公共函数
问题描述
我在 vue 中遇到了Computed setter,我发现它非常有用。为了完整起见,我将在此处复制并粘贴代码片段。
// ...
computed: {
fullName: {
// getter
get: function () {
return this.firstName + ' ' + this.lastName
},
// setter
set: function (newValue) {
var names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[names.length - 1]
}
}
}
// ...
这在我的情况下非常有效。唯一的问题是在几个组件上有相同的块,我不太喜欢这样。我更喜欢定义一个类似的方法GetOrSetFullName(newValue)
,然后在组件中简单地调用类似的方法
// ...
computed: {
fullName: GetOrSetFullName(newValue);
}
// ...
这是否可能,或者是否有其他标准化程序来避免多个组件上的重复代码块?
注意:以防万一。上面的代码是从 vue 网页复制粘贴的,但我使用的是打字稿。
解决方案
您可以在单独的对象中定义 getter/setter 并将其重用于您的心脏内容:
const fullNameComputer = {
get: function() {
return this.firstName + ' ' + this.lastName;
},
set: function(value) {
var names = value.split(' ');
this.firstName = names[0];
this.lastName = names[names.length - 1];
}
};
const app = new Vue({
el: '#app',
data: {
firstName: 'Foo',
lastName: 'Bar'
},
computed: {
fullName: fullNameComputer
}
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script>
<div id="app">
<input v-model.lazy="fullName">
<br>
{{ fullName }}
</div>
推荐阅读
- asp.net-core - Why is Asp.net core identity add migration is first dropping table and creating again
- html - 试图在表格上显示 div
- python - 为什么 *args 参数解包会给出一个元组?
- reactjs - 打字稿不能使用 animateMotion
- mysql - 查询以获取具有字段精确值的记录
- java - Entity in OneToMany collection is not updated
- python - 测试驱动开发
- javascript - React 无法弄清楚如何相应地向我的父母发送数据
- c# - Xamarin.Forms:绑定到 XAML 中的代码隐藏属性
- c++ - std::unordered_map 中的键与散列