我有a small app that lets you add, remove and edit recipes to a list of recipes .
添加路径为/add
,编辑路径为/edit
。我正在为两个 路由使用名为AddRecipe
的组件。
如果路由包含 'edit'
,组件的行为会略有不同 - 即输入字段已预先填充了您正在编辑的值。
这里是 AddRecipeForm.vue
,共享组件:
<template>
<div>
<form class="form">
<input v-model="recipe.name" placeholder="Recipe Name">
<textarea v-model="recipe.description" placeholder="Recipe Description..." rows="10"></textarea>
<button :disabled="nothingEntered()" @click.prevent="addRecipe">Submit</button>
</form>
</div>
</template>
<script>
export default {
name: 'AddRecipeForm',
data() {
return {
recipe: this.isEdit()
? this.$store.state.recipes[this.$route.params.id]
: {
name: '',
description: ''
}
}
},
methods: {
isEdit() {
return this.$route.path.includes('edit')
},
addRecipe() {
if (this.isEdit()) {
this.$store.dispatch('addRecipe', this.recipe)
} else {
this.$store.dispatch('addRecipe', {
id: Date.now(),
...this.recipe
})
}
this.$router.push('/')
},
nothingEntered() {
return !this.recipe.name || !this.recipe.description
}
},
}
</script>
我认为这个问题有更好的解决方案。例如,如果项目后期需要更多 View 也需要该组件怎么办?如果我想要一个漂亮、干净、可读的可重用组件,我不能一直检查组件中的路由。
处理需要相同 View 的路由的首选方式是什么?
最佳答案
当 if
过多时,一种常见的技术是使用配置映射(我编造了这个短语),例如
data() {
return {
configMap: {
add: {
addRecipe: function () {},
inputDisabled: false
},
edit: {
addRecipe: function () {},
inputDisabled: false
},
view: {
addRecipe: function () {},
inputDisabled: true
}
}
}
}
这里我们将条件(路由路径的一部分)映射到我们可以直接在该组件中使用的选项,因此我们可以在模板中编写 :disabled=configMap[routeType].inputDisabled
。
而在vue中,我们可以将inputDisabled
放在computed
中,将addRecipe
放在methods
中,声明起来更清晰,就像您在上面所做的那样。
如果add
,edit
的类型超出了路由,我们可以将类型定义为一个prop
并传入(如配置选项,就像我们对任何其他可重用组件一样)
关于routing - Vue 多用途组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41333605/