Recipe-Box Recipe模块

创建 images 目录,并放置一张图片当做默认图片,最好把 images 目录权限设置为 777(images的路径: public)


20180105174650.png

修改 路由文件 index.js (路径:resources/assets/js/router 下)

import Vue from 'vue';
import VueRouter from 'vue-router';

import Register from '../views/Auth/Register.vue';
import Login from '../views/Auth/Login.vue';

import RecipeIndex from '../views/Recipes/Index.vue';
import RecipeShow from '../views/Recipes/Show.vue';
import RecipeForm from '../views/Recipes/Form.vue';

Vue.use(VueRouter);

const router = new VueRouter({
    routes: [
        {path: '/register', component: Register},
        {path: '/login', component: Login},
        {path: '/', component: RecipeIndex},
        {path: '/recipes/create', component: RecipeForm, meta: {mode: 'create'}},
        {path: '/recipes/:id/edit', component: RecipeForm, meta: {mode: 'edit'}},
        {path: '/recipes/:id', component: RecipeShow}
    ]
});

export default router;

添加 Recipes 文件夹 并在该文件夹下创建 Index.vue 、Form.vue 和 Show.vue (创建Recipes文件夹 的 路径:/resources/assets/js/views)

Index.vue

<template>
    <div class="recipe__list">
        <div class="recipe__item" v-for="recipe in recipes">
            <router-link class="recipe__inner" :to="`/recipes/${recipe.id}`">
                <img :src="`/images/${recipe.image}`" v-if="recipe.image">
                <p class="recipe__name">{{recipe.name}}</p>
            </router-link>
        </div>
    </div>
</template>

<script type="text/javascript">
    import { get } from '../../helpers/api';
    export default{
        data(){
            return {
                recipes : []
            }
        },
        methods: {
        },
        created(){
            get('/api/recipes')
                .then((res) => {
                    this.recipes = res.data.recipes;
                })
                .catch((err) => {
                });
        }
    }
</script>

Form.vue

<template>
    <div class="recipe__show">

        <div class="recipe__header">
            <h3>{{action}} Recipe</h3>
            <div>
                <button class="btn btn__primary" @click="save" :disabled="isProcessing">Save</button>
                <button class="btn" @click="$router.back()" :disabled="isProcessing">Cancel</button>
            </div>
        </div>

        <div class="recipe__row">
            <div class="recipe__image">
                <div class="recipe__box">
                    <image-upload v-model="form.image"></image-upload>
                    <small class="error__control" v-if="error.image">{{error.image[0]}}</small>
                </div>
            </div>

            <div class="recipe__details" >
                <div class="recipe__details_inner">
                    <div class="form__group">
                        <label>Name</label>
                        <input type="text" class="form__control" v-model="form.name">
                        <small class="error__control" v-if="error.name">{{error.name[0]}}</small>
                    </div>

                    <div class="form__group">
                        <label>Description</label>
                        <textarea type="text" class="form__control" v-model="form.description"></textarea>
                        <small class="error__control" v-if="error.description">{{error.description[0]}}</small>
                    </div>

                </div>
            </div>
        </div>

        <div class="recipe__row">
            <div class="recipe__ingredients">
                <div class="recipe__box">
                    <h3 class="recipe__sub_title">Ingredients</h3>
                    <div v-for="(ingredient, index) in form.ingredients" class="recipe__form">
                        <input type="text" class="form__control" v-model="ingredient.name"
                               :class="[error[`ingredients.${index}.name`] ? 'error__bg' : '']">

                        <input type="text" class="form__control form__qty" v-model="ingredient.qty"
                               :class="[error[`ingredients.${index}.qty`] ? 'error__bg' : '']">

                        <button class="btn btn__danger" @click="remove('ingredients', index)">
                            &times;
                        </button>
                    </div>

                    <button class="btn" @click="addIngredient">Add Ingredient</button>
                </div>
            </div>

            <div class="recipe__directions">
                <div class="recipe__directions_inner">
                    <h3 class="recipe__sub_title">Directions</h3>
                    <div v-for="(direction, index) in form.directions" class="recipe__form">
                    <textarea type="text" class="form__control" v-model="direction.description"
                              :class="[error[`directions.${index}.description`] ? 'error__bg' : '']"></textarea>

                        <button class="btn btn__danger" @click="remove('directions', index)">
                            &times;
                        </button>
                    </div>

                    <button class="btn" @click="addDirection">Add Direction</button>
                </div>
            </div>
        </div>

    </div>
</template>

<script type="text/javascript">
    import Vue from 'vue';
    import Flash from '../../helpers/flash';
    import { get, post } from '../../helpers/api';
    import { toMulipartedForm } from '../../helpers/form';
    import ImageUpload from '../../components/ImageUpload.vue';
    export default{
        data(){
            return {
                form: {
                    ingredients: [],
                    directions: []
                },
                error: {},
                isProcessing: false,
                initializeURL: `/api/recipes/create`,
                storeURL: `/api/recipes`,
                action: 'Create'
            }
        },
        components:{
            ImageUpload
        },
        methods: {
            save(){
                this.isProcessing = true;
                const form = toMulipartedForm(this.form, this.$route.meta.mode);
                post(this.storeURL, form)
                    .then((res) => {
                        if(res.data.saved){
                            Flash.setSuccess(res.data.message);
                            this.$router.push(`/recipes/${res.data.id}`);
                        }
                    }).catch((err) => {
                        if(err.response.status === 422){
                            this.error = err.response.data;
                        }
                        this.isProcessing = false;
                    })
            },
            addDirection(){
                this.form.directions.push({description: ''});
            },
            addIngredient(){
                this.form.ingredients.push({
                    name: '',
                    qty: ''
                });
            },
            remove(type, index){
                if(this.form[type].length > 1){
                    this.form[type].splice(index, 1);
                }
            }
        },
        created(){
            if(this.$route.meta.mode === 'edit') {
                this.initializeURL = `/api/recipes/${this.$route.params.id}/edit`;
                this.storeURL = `/api/recipes/${this.$route.params.id}?_method=PUT`;
                this.action = 'Update';
            }
            get(this.initializeURL).then((res) => {
                Vue.set(this.$data, 'form', res.data.form);
            }).catch((err) => {
                console.log(err);
            })
        }
    }
</script>

Show.vue

<template>
    <div class="recipe__show">
        <div class="recipe__row">
            <div class="recipe__image">
                <div class="recipe__box">
                    <img :src="`/images/${recipe.image}`" v-if="recipe.image" width="340px;">
                </div>
            </div>

            <div class="recipe__details">
                <div class="recipe__details_inner">
                    <small>Submitted by: {{recipe.user.name}}</small>
                    <h1 class="recipe__title">{{recipe.name}}</h1>
                    <p class="recipe__description">{{recipe.description}}</p>
                    <div v-if="auth.api_token && auth.user_id === recipe.user_id">
                        <router-link :to="`/recipes/${recipe.id}/edit`" class="btn btn-primary">
                            Edit
                        </router-link>

                        <button class="btn btn__danger" @click="remove" :disabled="isRemoving">Delete</button>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="recipe__row">
            <div class="recipe__ingredients">
                <div class="recipe__box">
                    <h3 class="recipe__sub_title">Ingredients</h3>
                    <ul>
                        <li v-for="ingredient in recipe.ingredients">
                            <span>{{ingredient.name}}</span>
                            <span>{{ingredient.qty}}</span>
                        </li>
                    </ul>
                </div>
            </div>

            <div class="recipe__directions">
                <div class="recipe__directions_inner">
                    <h3 class="recipe__sub_title">Directions</h3>
                    <ul>
                        <li v-for="(direction, i) in recipe.directions">
                            <p>
                                <strong>{{i + 1}}</strong>
                                {{direction.description}}
                            </p>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</template>

<script type="text/javascript">
    import Auth from '../../store/auth';
    import Flash from '../../helpers/flash';
    import { get, del} from '../../helpers/api';
    export default{
        data(){
            return {
                auth: Auth.state,
                isRemoving: false,
                recipe: {
                    user: {},
                    ingredients: [],
                    directions: []
                }
            }
        },
        methods: {
            remove(){
                this.isRemoving = false;
                del(`/api/recipes/${this.$route.params.id}`)
                    .then((res) =>{
                        if (res.data.deleted){
                            Flash.setSuccess('删除操作成功!');
                            this.$router.push('/');
                        }
                    }).catch((err) => {
                });
            }
        },
        created(){
            console.log(this.$route.params);
            get(`/api/recipes/${this.$route.params.id}`)
                .then((res) =>{
                    this.recipe = res.data.recipe;
                }).catch((err) => {
            })
        }
    }
</script>

在 components 文件夹下创建 ImagePreview.vue 和 ImageUpload.vue(路径:/resources/assets/js/components/)

ImagePreview.vue

<template>
    <div class="image__preview" v-if="image">
        <img :src="image">
        <button class="btn btn__danger image__close" @click="$emit('close')">&times;</button>
    </div>
</template>

<script type="text/javascript">
    export default{
        data(){
            return {
                image: null
            }
        },
        props: {
            preview: {
                type: [String, File],
                default: null
            }
        },
        watch: {
            'preview': 'setPreview'
        },
        methods: {
            setPreview(){
                if(this.preview instanceof File){
                    const fileReader = new FileReader;
                    fileReader.onload = (event) => {
                        this.image = event.target.result;
                    };
                    fileReader.readAsDataURL(this.preview);
                }else if(typeof this.preview === 'string'){
                    this.image = `images/${this.preview}`;
                }else {
                    this.image = null;
                }
            }
        },
        created(){
            this.setPreview();
        }
    }
</script>

ImageUpload.vue

<template>
    <div class="image">
        <image-preview :preview="value" @close="$emit('input', null)" v-if="value"></image-preview>
        <div class="image__upload" v-else>
            <input type="file" accept="images/*" @change="upload">
        </div>
    </div>
</template>

<script type="text/javascript">
    import ImagePreview from './ImagePreview.vue';
    export default{
        props: {
            value: {
                type: [String, File],
                default: null
            }
        },
        components: {
            ImagePreview
        },
        methods: {
            upload(e){
                const files = e.target.files;
                console.log(files);
                if(files && files.length > 0){
                    this.$emit('input', files[0]);
                }
            }
        }
    }
</script>
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 222,252评论 6 516
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,886评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,814评论 0 361
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,869评论 1 299
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,888评论 6 398
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,475评论 1 312
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 41,010评论 3 422
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,924评论 0 277
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,469评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,552评论 3 342
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,680评论 1 353
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,362评论 5 351
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 42,037评论 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,519评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,621评论 1 274
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 49,099评论 3 378
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,691评论 2 361

推荐阅读更多精彩内容

  • 修改 welcome.blade.php 文件 (路径:resources/views/welcome.blade...
    三仕贰號阅读 405评论 0 0
  • jHipster - 微服务搭建 CC_简书[https://www.jianshu.com/u/be0d56c4...
    quanjj阅读 816评论 0 2
  • 本文基于工作项目开发,做的整理笔记因工作需要,项目框架由最初的Java/jsp模式,逐渐转移成node/expre...
    SeasonDe阅读 7,447评论 3 35
  • 响应式布局的理解 响应式开发目的是一套代码可以在多种终端运行,适应不同屏幕的大小,其原理是运用媒体查询,在不同屏幕...
    懒猫_6500阅读 790评论 0 0
  • 去上村得走两里地,要穿过长一段无人的山路,路过一座石桥,一座小石庙,爬一条长坡和一片古老秘林。对于当时小小的而言,...
    李子香香阅读 348评论 0 0