vue正在将对象子级转义为参数



我想构建一个助手函数来减少多余的代码行。我不想一遍又一遍地做几乎相同的事情,而是想用这个函数简单地添加一个参数并减少代码行。

<template>
<div>
<!-- TODO: ADD ALL PROPS NOW! -->
<UserInfo
:user-name="userData.userName"
:budget="userData.budget"
:leftover="userData.leftover"
/>
<UserIncExp />
</div>
</template>
<script>
import UserInfo from '../User/UserInfo.vue';
import UserIncExp from '../User/UserIncExp/_UserIncExp.vue';
export default {
components: {
UserInfo,
UserIncExp
},
data() {
return {
test: '',
userData: {
userName: '',
budget: '',
leftover: '',
inc: [],
exp: [],
active: false
}
};
},
computed: {},
watch: {
'$route.params.userId': {
handler() {
this.loadUserDataFromState();
}
},
immediate: true
},
created() {
this.loadUserDataFromState();
},
methods: {
loadUserDataFromState() {
// this.userData.userName = this.$store.state.users[this.$attrs.userId].userName;
// this.userData.budget = this.$store.state.users[this.$attrs.userId].salery;
// this.userData.leftover = this.$store.state.users[this.$attrs.userId].leftover;
this.helper(userName);
},
// CHECK HERE <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
helper(data) {
return this.userData.data = this.$store.state.users[this.$attrs.userId].data;
}
}
};
</script>
<style>
</style>

但我不明白为什么我不能使用data作为参数,然后在执行的函数中使用它

使用括号表示法,如:

loadUserDataFromState() {
this.helper("userName");
},
helper(key) {
this.userData[key] = this.$store.state.users[this.$attrs.userId][key];
}

helper需要一个密钥(它是一个字符串(。

注意:helper不需要返回任何内容。


一种根本不需要函数helper的替代方法是在键数组上使用循环,如下所示:

loadUserDataFromState() {
for(let key of ["userName", "salery", "leftover"]) {
this.userData[key] = this.$store.state.users[this.$attrs.userId][key];
}
}

它只是在数组CCD_ 5中的键上循环并将值从源对象动态复制到CCD_。

最新更新