Home > database >  How to use vue getters to find a value inside an object?
How to use vue getters to find a value inside an object?

Time:12-03

I want to get a specific value of an object inside the state of vuex.

Let me show you what I mean:

import { createStore } from "vuex";

export default createStore({
    state: {
        cards: [{
                title: "Blog 1",
                htmlCode: "This is blog 1",
                index: 1,
            },
            {
                title: "Blog 2",
                htmlCode: "This is blog 2",
                index: 2,
            },
            {
                title: "Blog 3",
                htmlCode: "This is blog 3",
                index: 3,
            },
            {
                title: "Blog 4",
                htmlCode: "This is blog 4",
                index: 4,
            },
            {
                title: "Blog 5",
                htmlCode: "This is blog 5",
                index: 5,
            },
            {
                title: "Blog 6",
                htmlCode: "This is blog 6",
                index: 6,
            },
            {
                title: "Blog 7",
                htmlCode: "This is blog 7",
                index: 7,
            },
        ],
    },
    getters: {
      getTodoById: (state) => (id) => {
        return state.cards.find(todo => todo.index === id)
      }
    },
    mutations: {},
    actions: {},
    modules: {},
});

Now if I insert this value in my code: <p>{{ this.$store.getters.getTodoById(2) }}</p>, I get this as result: { "title": "Blog 2", "htmlCode": "This is blog 2", "index": 2 } What I want, is the value of for examplehtmlCode and that result would be This is blog 2.

Hopefully someone understands what I mean.

For clarity: I want this result in the browser: This is blog 2

It is very important for my website that it is done with vuex getters.

CodePudding user response:

This is a posible solution

getTodoById: (state) => (id) => {
  const todo = state.cards.find(todo => todo.index === id)
  return todo.htmlCode
}

Other solution is create a todo data in the componente and in the created() add your getter and asign to this data.

  data() {
    return {
      todo: null,
    };
  },
  created() {
    this.todo = this.$store.getters.getTodoById(id) // for example extracted by the route
  },
<p>{{ todo.htmlCode }}</p>

CodePudding user response:

This should work.

<p>{{ this.$store.getters.getTodoById(2).htmlCode}}</p>
  • Related