[Vuejs]-How to display item vue when i click on vue listing all items?

0👍

You can write in this way.

<template>
  <main class="portrait individual">
    <h1 v-if="portrait">{{ portrait.title.rendered }}</h1>
  </main>
</template>

<script>
export default {
  computed: {
    portraits() {
      return this.$store.state.portraits;
    },
    portrait() {
      return this.portraits.find(el => el.slug === this.slug);
    }
  },
  data() {
    return {
      slug: this.$route.params.slug
    };
  },
  created() {
    this.$store.commit("getPortraits");
  }
};
</script>

It seems this.$store.dispatch("getPortraits"); is not invoked.

Instead of that, You can use this.$store.commit("getPortraits"); in created().

In store/index.js.

export const state = () => ({
  portraits: []
});

export const mutations = {
  getPortraits(state) {
    state.portraits.push({
      slug: "a",
      title: {
        rendered: "hello"
      }
    });
  }
};

I tried in this sandbox.

In another way, you can also use portraits data in data() object.

<template>
  <main class="portrait individual">
    <h1 v-if="portrait">{{ portrait.title.rendered }}</h1>
  </main>
</template>

<script>
export default {
  computed: {
    portrait() {
      return this.portraits.find(el => el.slug === this.slug);
    }
  },
  data() {
    return {
      slug: this.$route.params.slug,
      portraits: this.$store.state.portraits
    };
  },
  created() {
    this.$store.commit("getPortraits");
  }
};
</script>

And use v-if="portrait" in h1 tag because portrait object might be initial value like undefined or empty array.

Leave a comment