Как передать обновленные данные уже обработанному дочернему компоненту vue - PullRequest
0 голосов
/ 21 февраля 2019

Я пытаюсь обновить некоторые переменные в компонент от родителя.Моя ситуация такова:

У меня есть родительский компонент:

    import LugarListComponent from './LugarListComponent';
    import LugarAddComponent from './LugarAddComponent'

    export default {
        components:{
            'lugar-list-component' : LugarListComponent,
            'lugar-add-component' : LugarAddComponent,
        },
        data(){
            return {
                show: false,
                nombre: '',
                desc : '',
            }
        },
        methods:{
            showComponent: function () {
                this.show = true;
            },
            hideComponent: function () {
                this.show = false;
            },
            setLugar: function(lugar){
                this.show = true;
            }
        },
        mounted() {
            //console.log('Component mounted.')
        }
    }
<template>
    <div class="container">
        <h3>Lugares</h3>

        <div style="text-align: right">
            <button type="button" class="btn btn-primary" v-show="!show" v-on:click.prevent="showComponent"><i class="fa fa-plus"></i> Adicionar</button>
            <button type="button" class="btn btn-success" v-show="show" v-on:click.prevent="hideComponent"><i class="fa fa-arrow-left"></i> Regresar</button>
        </div>
        <br>

        <lugar-list-component v-show="!show" @setLugar="setLugar"></lugar-list-component>
        <lugar-add-component v-show="show" @hideComponent="hideComponent"></lugar-add-component>
    </div>
</template>

Этот компонент имеет два дочерних компонента: lugar-list для списка мест и lugar-add для добавления места.У меня есть show var для контроля, когда я показываю один из них.

Я хочу отредактировать место, но я хочу отправить данные в lugar-add для отображения его значений в этом компоненте, но я ненайти любое решение для обновления Vars в Lugar-Add.Здесь я показываю код этих компонентов.

Для lugar-add

export default {
        data(){
            return {
                image: '',
                nombre: '',
                desc : ''
            }
        },
        methods: {
            onImageChange(e) {
                let files = e.target.files || e.dataTransfer.files;
                if (!files.length)
                    return;
                this.createImage(files[0]);
            },
            createImage(file) {
                let reader = new FileReader();
                let vm = this;
                reader.onload = (e) => {
                    vm.image = e.target.result;
                };
                reader.readAsDataURL(file);
            },
            uploadImage(){
                axios.post('/lugar',{
                    image: this.image,
                    nombre: this.nombre,
                    desc: this.desc
                }).then(response => {
                    if(response.status == 200){
                        this.$emit('hideComponent')
                    }
                });
            },
            setAttributes(lugarEdit){
                console.log('disparado');
                this.nombre = lugarEdit.nombre;
                this.desc = lugarEdit.desc;
            }
        },
        mounted() {
            //console.log('Component mounted.');
            this.$on(
                'setAttributes',
                function(lugar) {
                    this.nombre = lugar.nombre;
                    this.desc = lugar.desc;
                }
            );
        }
<template>
    <div class="container">
        <div class="form-group">
            <label>Nombre</label>
            <input type="text" v-model="nombre" class="form-control" placeholder="Nombre del lugar">
        </div>

        <div class="form-group">
            <label for="descTexArea">Descripci&oacute;n</label>
            <textarea v-model="desc" class="form-control" id="descTexArea" rows="3"></textarea>
        </div>

        <div class="form-group">
            <label for="exampleFormControlFile1">Subir im&aacute;genes</label>
            <input type="file" v-on:change="onImageChange" class="form-control-file" id="exampleFormControlFile1">
        </div>

        <div class="form-group">
            <button type="button" class="btn btn-primary" @click="uploadImage">Adicionar</button>
        </div>


        <div class="col-md-3" v-if="image">
            <img :src="image" class="img-responsive" height="70" width="90">
        </div>
    </div>
</template>

Здесь я использую событие, чтобы скрыть этот компонент и показать компонент lugar-list.Вот код для lugar-list

export default {
        name: 'lugar-list-component',
        data:function(){
            return {
                listLugares : [],
                id : '',
            }
        },
        methods:{
            getLugares: function () {
                fetch('/lugar')
                    .then(response => response.json())
                    .then(res => {
                        this.listLugares = res;
                    })
            },
            setId: function(id){
                this.id = id;
            },
            removeLugar: function(id){
                this.id = id;
                axios.delete('lugar/'+id)
                    .then(response => {
                        this.getLugares();
                    });
            },
            editLugar: function(id){
                this.id = id;

                axios.get('lugar/'+id)
                    .then(response => {
                        this.$emit('setLugar',response);
                    });
            },
        },
        mounted() {
            this.getLugares();
        }
    }
<template>
    <div class="container">

        <table class="table table-striped">
            <thead>
            <tr>
                <th scope="col">#</th>
                <th scope="col">Nombre</th>
                <th scope="col">Desc.</th>
                <th scope="col">Fecha</th>
                <th scope="col">Acciones</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(item, index) in listLugares">
                <th scope="row">{{ index+1 }}</th>
                <td>{{ item.nombre }}</td>
                <td>{{ item.desc }}</td>
                <td>{{ item.created_at }}</td>
                <td>
                    <button type="button" class="btn btn-success" v-on:click.prevent="editLugar(item.id)"><i class="fa fa-edit"></i> Editar</button>
                    <button type="button" class="btn btn-danger" v-on:click.prevent="removeLugar(item.id)"><i class="fa fa-remove"></i> Eliminar</button>
                </td>
            </tr>

            </tbody>
        </table>


    </div>
</template>

Я надеюсь, что вы меня понимаете.Спасибо.

Ответы [ 2 ]

0 голосов
/ 25 февраля 2019

Я не нахожу другого решения, использующего маршруты с параметрами, я считаю, что это лучшее решение.

Вот мои маршруты

{
        path: '/lugar', component: require('./components/lugar/LugarComponent').default,
        children: [
            { path: '', component: LugarList },
            {
                path: 'add/:id?',
                name: 'lugarAdd',
                component: LugarAdd
            },
            {
                path: 'list',
                component: LugarList
            }
        ]
    }

Маршрут для добавления места имеет необязательный параметр.

Теперь, в компонент Add, я получаю параметр с этим кодом:

this.id = this.$route.params.id;
                this.modeEdit = true;

                axios.get('/lugar/'+this.id)
                    .then(response => {
                        this.nombre = response.data.nombre;
                        this.desc = response.data.desc;

                        for(let i = 0; i<response.data.images.length; i++){
                            this.image.push(response.data.images[i]);
                        }
                    });

Когда я получаю идентификатор места, я запрашиваю его информацию с помощью axios.

0 голосов
/ 21 февраля 2019

Создайте событие из 1-го дочернего компонента, чтобы обновить реквизит родителя.Затем передайте значение, которое вы хотите обновить как реквизит, дочернему элементу secund.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...