Y
Y
Yevhenii K2020-07-12 17:15:31
JavaScript
Yevhenii K, 2020-07-12 17:15:31

How to get data before component render?

There is a component that displays the results in the form of a table. The problem is that an empty table is rendered first, and then data is added. How to make table output after getting data?

<template>
  <div>
    <!-- <p>Count: {{ brandsCounter }}</p> -->
    <el-table :data="getAllBrands">
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="name" label="Name"></el-table-column>
      <el-table-column>
        <template slot-scope="props">
          <el-button type="danger" icon="el-icon-delete" @click="deleteBrand(props.row.id)"></el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

    <script>
import { mapGetters, mapActions } from "vuex";
export default {
  name: "BrandsTable",
  computed: {
    ...mapGetters(["getAllBrands"])
  },
  methods: {
    ...mapActions(["requestBrands", "deleteBrand"])
  },
  mounted: function() {
    this.requestBrands();
  }
};
</script>

Vuex
import store from "..";

export default {
  state: {
    all: []
  },
  getters: {
    getAllBrands: state => {
      return state.all;
    }
  },
  mutations: {
    setBrands(state, brands) {
      state.all = brands;
    },
    deleteBrandFromList(state, brandId) {
      state.all = state.all.filter(b => b.id !== brandId);
    }
  },
  actions: {
    async requestBrands(ctx) {
      await axios
        .get("/admin/brands", {
          _token: store.state.token
        })
        .then(function(response) {
          ctx.commit("setBrands", response.data.brands);
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    async deleteBrand(ctx, id) {
      await axios
        .post("/admin/brands/" + id, {
          _token: store.state.token,
          _method: "DELETE"
        })
        .then(function() {
          ctx.commit("deleteBrandFromList", id);
        })
        .catch(function(error) {
          console.log(error);
        });
    }
  }
};

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya, 2020-07-12
Hrebet @hrebet

//
<ElTable
  v-if="getAllBrands.length > 0"
  :data="getAllBrands"
>
//

D
Dima Pautov, 2020-07-12
@bootd

<el-table
  v-if="getAllBrands.length"
  :data="getAllBrands"
>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question