【问题标题】:Pass datas to another component in Vuejs?将数据传递给 Vuejs 中的另一个组件?
【发布时间】:2021-12-07 11:12:07
【问题描述】:

我有这个过滤功能(属于一个List组件),然后我需要将结果传递给另一个组件,(它们是兄弟)来填充我的DataTable(父组件):

async filtroVariaveis () {
                try {
                    this.loading = true;

                    this.variaveis = await this.variaveisService.listVariables();

                    let idGrupos = null;
                    if (!this.grupos[0] && this.maquinaSelecionada[0]) {
                        idGrupos = this.gruposOpcoes.map(m => m.id);
                    }

                    if (!this.grupos[0] && !this.maquinaSelecionada[0] && this.areaSelecionada[0]) {
                        const idMaquinas = this.maquinasOpcoes.map(m => m.id);
                        const grupo = this.gruposOpcoes.filter(a => idMaquinas.includes(a.id_maquina));

                        idGrupos = grupo.map(a => a.id);
                    }

                    if (this.grupos[0]) {
                        idGrupos = this.grupos.map(g => g.id);
                    }

                    const tipos = this.tipoVariavel.map(t => t === "Analógica" ? t = "ANALOGICA" : "DIGITAL");
                    const tag = this.tagInput || this.variaveis.map(t => t.tag);
                    const descricao = this.descricaoInput || this.variaveis.map(d => d.descricao);

                    this.filtroAplicado = ((await this.variaveisService.listVariables(idGrupos, tipos, tag, descricao)) || []);
                } catch (err) {
                    console.log(err);
                }

this.variaveisService 是与我的 API 通信的 Axios 服务。

我的列表组件:

<template>
<two-cards>
        <template #header>
            <h4 class="card-title">Filtros</h4>
            <slot>
                <router-link
                    to="/variaveis/add"
                    class="btn btn-success text-white align-self-center"
                >
                Adicionar variável
                </router-link>
            </slot>
        </template>
        <template #one>
            <form class="mt-2" @submit.prevent="filtroVariaveis">
                <div class="form-row">
                    <div class="col form-group col-sm-6">
                        <label for="data-final">Tag: </label>
                        <b-form-input
                            v-model="tagInput"
                            id="data-final"
                            input-class="bg-white"
                        ></b-form-input>
                    </div>
                    <div class="col form-group col-sm-6">
                        <label for="data-inicial">Descrição: </label>
                        <b-form-input
                            v-model="descricaoInput"
                            id="data-inicial"
                            input-class="bg-white"
                        ></b-form-input>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group col-sm-3">
                        <label class="mt-2">Área </label>
                            <vue-multi-select
                                class="multi-100"
                                v-model="areaSelecionada"
                                @input="checarArea"
                                search
                                historyButton
                                :options="{ multi: false, labelName: 'nome' }"
                                :selectOptions="areasOpcoes"
                                :btnLabel="() => areaSelecionada[0] ? areaSelecionada[0].nome : 'Selecione'"
                            />
                    </div>
                    <div class="form-group col-sm-3">
                        <label class="mt-2">Máquina </label>
                            <vue-multi-select
                                class="multi-100"
                                v-model="maquinaSelecionada"
                                :disabled="!areaSelecionada[0]"
                                @input="checarMaquina"
                                search
                                historyButton
                                :options="{ multi: true, labelName: 'nome' }"
                                :selectOptions="maquinasOpcoes"
                                :btnLabel="() => customLabel(maquinaSelecionada)"
                            />
                    </div>
                    <div class="form-group col-sm-3">
                        <label class="mt-2">Grupo </label>
                            <vue-multi-select
                                class="multi-100"
                                v-model="grupos"
                                search
                                historyButton
                                :options="{ multi: true }"
                                :selectOptions="gruposOpcoes"
                                :btnLabel="() => customLabel(grupos)"
                            />
                    </div>
                    <div class="form-group col-sm-3">
                        <label class="mt-2">Tipo</label>
                            <vue-multi-select
                                class="multi-100"
                                v-model="tipoVariavel"
                                search
                                historyButton
                                :options="{ multi: true }"
                                :selectOptions="tiposOpcoes"
                                :btnLabel="() => customLabel(tipoVariavel)"
                            />
                    </div>
                </div>
                <div class="d-flex justify-content-end tcs-card-footer-action">
                    <button
                        class="btn btn-success tcs-btn"
                        type="search"
                    >
                        <SearchIcon />
                    </button>
                </div>
            </form>
        </template>
        <template #two>
            <GenericList
                title="variáveis"
                :linhas="linhas"
                data-table-state-name="Variável"
                add-route="add_variavel"
                edit-route="edit_variavel"
                :cols="['#', 'Tag', 'Descrição', 'Tipo']"
                :cols-name="['id', 'tag', 'descricao', 'tipo']"
                :cols-map="i => [i.id, i.tag, i.descricao, i.tipo]"
            />
        </template>
    </two-cards>
</template>

computed: {
            linhas () {
                return this.lista.map((row) => ({
                    href: { name: this.editRoute, params: { id: row.id }},
                    cols: this.colsMap(row)
                }));
            }
        },

我的 GenericList 组件,我需要在其中放置这些数据:

<template>
    <div>
        <DataTable
            scroll
            :async="pagination"
            :loading="loading"
            :colunas="parsedCols"
            :linhas="linhas"
            :errMsg="errMsg"
            :state="dataTableState"
            @state-change="setStateDataTable"
        >
            <template #results-page v-if="pagination">
                <select
                    class="custom-select ml-1"
                    :value="results"
                    @input="changeResults"
                    data-cy="resultados-pagina"
                >
                    <option value="10">10 por página</option>
                    <option value="20">20 por página</option>
                    <option value="50">50 por página</option>
                    <option value="100">100 por página</option>
                    <option v-if="canShowAllResults" value="-1">
                        Mostrar todos
                    </option>
                </select>
            </template>
            <template v-for="col in cols" v-slot:[col]="{ value, item }">
                <slot :name="col" :value="value" :item="item">
                    <router-link
                        v-if="value && value.rota && value.nome && value.id"
                        :to="{ name: value.rota, params: { id: value.id } }"
                        title="Ir para a edição"
                        >
                        <edit-icon size="16" /> {{ value.nome }}</router-link
                    >
                </slot>
            </template>
        </DataTable>
        <Paginator
            :page="page"
            :pages="pages"
            :count="count"
            :disabled="loading"
            :first="first"
            :last="last"
            @paginate="paginate"
        />
    </div>
</template>

props: {
        loading: Boolean,

        title: {
            type: String,
            required: true
        },

        addRoute: {
            type: String,
            required: true
        },

        editRoute: {
            type: String,
            required: true
        },

        dataTableStateName: {
            type: String,
            required: true
        },

        lista: {
            type: Array
        },

        linhas: {
            type: Array
        },

        cols: {
            type: Array,
            required: true
        },

        colsMap: {
            type: Function,
            required: true
        },

        colsName: {
            type: Array,
            required: true
        },

        canShowAllResults: {
            type: Boolean,
            default: false
        },

        showInativos: {
            type: Boolean,
            default: false
        }
    },

data () {
    return {
        errMsg: "",

        pagination: false,
        page: 0,
        pages: 1,
        results: 20,
        first: 0,
        last: 0,
        count: 0
    };
},

computed: {
    dataTableState () {
        return this.$store.state.dataTables[
            "dataTable" + this.dataTableStateName
        ];
    },

    parsedCols () {
        return this.cols.map((c, idx) => this.colsName[idx] ? c : { value: c, sortable: false }
        );
    }
},

我不知道如何填写这个DataTable,有人可以帮助我吗?

【问题讨论】:

  • 取决于 2 个组件的位置。组件是兄弟吗?还是父母对孩子?
  • @ElsaKarami 他们是兄弟姐妹..

标签: javascript node.js vue.js axios


【解决方案1】:

您可以使用$emit$on 在兄弟组件之间传递数据。 请看这个例子

当你将数据传递给另一个组件时,你必须设置这一行:

this.$root.$emit('eventing', data);

然后,你可以像这个例子一样将数据接收到目标组件中:

1)

mounted() {
  this.$root.$on('eventing',this.functionName);
}

2)

mounted() {
    this.$root.$on('eventing', data => {
        console.log(data);
    });
}

请注意,你最好在目标组件中设置$off

1)

 beforeDestroy() {
    this.$root.$off("eventing", this.functionName);
  }

2)

beforeDestroy() {
  this.$root.$off("eventing");
}

你可以在this.functionName的参数中找到你需要的数据

【讨论】:

  • this.$root.$emit('eventing', data);在 GenericList 页面中,您需要设置 $on 如下:mounted() { this.$root.$on('eventing', data =&gt; { console.log(data); }); }
  • 这似乎可行,谢谢艾尔莎!控制台已经向我展示了我想要的东西,但我仍然不知道如何用这个结果填写表格,如果你能帮助我,我真的很感激......
  • 谢谢。您需要在表格标签内设置 v-if 。因为在调用发出之前表格呈现
  • 在我的通用列表组件中:mounted () { this.$root.$on("filtroVariaveis", data =&gt; { this.pagination = true; console.log(data); }); }
  • 你可以这样设置: beforeDestroy() { this.$root.$off("filtroVariaveis"); } 安装后的部分
猜你喜欢
  • 2018-09-05
  • 2019-01-31
  • 2018-09-12
  • 1970-01-01
  • 2019-09-29
  • 1970-01-01
  • 1970-01-01
  • 2018-01-16
  • 2018-10-21
相关资源
最近更新 更多