0

How to pass an input field to the getter?

I'm trying to pass th einput field to the getter as a paramether. How to pass the param to the getter ?

<input
      type="text"
      placeholder="Search here"
      v-model="search"
      :input=event.target.value"
    />


export const mutations = {
  setProducts(state, data) {
    state.products = data;
  },

export const actions = {
  async getProducts(context) {
    const res = await fetch(...

      context.commit('setProducts', result);
 
  },
}

1 Answer 1

1

Getters are basically computed properties for the vuex store. They take the state as their first argument and other getters as their second argument. If you want to send something as parameters to the store and then perform operations on it, you would have to define an action in the store and then call that action in your component and pass whatever data you need to, to it. Getters are meant to access your vuex state and return them to your component.

Example getter: store.js

    //initialize the store
    state: {
      todos: []
    },
    actions: {
      getTodos(/*data from component*/) {
        //set data in todos state and call this action in your component
        state.todos = //data from component
     }
    },
    getters: {
      todos(state) {
        return state.todos;
      }
    }

Edit:

Here's how your component file would look like.

component.vue

    <input
      type="text"
      placeholder="Search here"
      v-model="search"
     />

    <script>
    import { ref } from 'vue';
    import { getProducts } from '../store';

    const search = ref('');

    const products = () => {
        getProducts(search.value);
    }
    </script>

store.js

    export const state = () => ({
      products: [],
    });
    
    export const mutations = {
      setProducts(state, data) {
        state.products = data;
      },
    }
    export const actions = {
      async getProducts({ commit }, search) {
        const result = await fetch()
        //perform filter logic here
        commit('setProducts', result);
      },
    }
    export const getters = {
      getProducts(state) {
        return state.products;
      },
    };

Make sure to use the getter inside a computed property in your component.

Note that this code is based on Vue 3

Sign up to request clarification or add additional context in comments.

2 Comments

Yhe main issue is to filter the initial array if true (data passed from the component) and if false need to show the initial array withou filtering. Please see I've edited the initial question code.
I have edited my answer and added code for your problem, hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.