Routing Vue多用途组件?
我有 添加有路由Routing Vue多用途组件?,routing,vue.js,Routing,Vue.js,我有 添加有路由/add,编辑有路由/edit。我正在使用一个名为AddRecipe的组件来处理两条路由 如果路由包含“编辑”,则组件的行为会略有不同,即输入字段预先填充了您正在编辑的值 下面是共享组件AddRecipeForm.vue: <template> <div> <form class="form"> <input v-model="recipe.name" placeholder="Recipe
/add
,编辑有路由/edit
。我正在使用一个名为AddRecipe
的组件来处理两条路由
如果路由包含“编辑”
,则组件的行为会略有不同,即输入字段预先填充了您正在编辑的值
下面是共享组件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>
提交
导出默认值{
名称:“AddRecipeForm”,
数据(){
返回{
配方:this.isEdit()
?此.$store.state.recipes[此.$route.params.id]
: {
名称:“”,
说明:“”
}
}
},
方法:{
isEdit(){
返回此。$route.path.includes('edit'))
},
addRecipe(){
if(this.isEdit()){
此.store.dispatch('addRecipe',this.recipe)
}否则{
此.$store.dispatch('addRecipe'{
id:Date.now(),
…这是我的食谱
})
}
这是。$router.push(“/”)
},
虚无的{
return!this.recipe.name | |!this.recipe.description
}
},
}
我认为有更好的办法来解决这个问题。例如,如果项目中以后需要更多视图,并且这些视图也需要该组件,该怎么办?如果我想要一个干净易读的可重用组件,我就不能一直检查组件中的路由
处理需要相同视图的路由的首选方法是什么?如果您从哪个状态查看,如果您有两个理由更改一个类(在您的情况下是组件),则必须将功能分为两个类。它可能看起来像一个过载的组件
然而,考虑到当前所涉及的逻辑的简单性,这似乎是一个很好的解决方案,直到您可以将逻辑封装在一个函数中,如
isEdit
,但如果出现更多不同类型的检查,您可以创建两个或多个单独的组件,如AddRecipeForm
/EditRecipeForm
等,每个组件都可以做一件事。获取太多时的一种常见技术是使用配置映射(我编造了这个短语),例如
在这里,我们将条件(路由路径的一段)映射到可以直接在此组件中使用的选项,这样我们就可以在模板:disabled=configMap[routeType].inputDisabled
中写入
在vue中,我们可以将inputDisabled
放在computed
中,将addRecipe
放在方法中,以便更清楚地声明它们,就像上面所做的那样
如果add
,edit
的类型超出了路由,我们可以将该类型定义为prop
,并将其传入(作为配置选项,就像我们将任何其他可重用组件一样)
data() {
return {
configMap: {
add: {
addRecipe: function () {},
inputDisabled: false
},
edit: {
addRecipe: function () {},
inputDisabled: false
},
view: {
addRecipe: function () {},
inputDisabled: true
}
}
}
}