routing - Vue 多用途组件?

标签 routing vue.js

我有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/

相关文章:

ruby-on-rails-3 - 如何在 Rails 3 中创建一个自定义 Controller Action 的路由?

javascript - React Router 4 的默认路由

vue.js - Vuetify v-data-table - 如何使其填充可用高度?

laravel - dd() 在 vue-laravel 项目 axios 调用中不起作用。是否可以在 axios 调用中使用转储?

ruby-on-rails-3 - Rails 3 不在公用文件夹中查找 Assets On Show 方法

c# - 在与请求匹配的 Controller 上未找到任何操作

javascript - 在 Vue.js v2.x 中使用 v-for 指令时如何指定范围的起始值?

javascript - Array.prototype.filter - 是否可以使用多个条件过滤多个条件? [JS、VueJS]

android - 带 map 和路线的 Android 项目要使用哪些库?

javascript - 使用 $set 后 VueJS 不更新 View