Home > other >  vuex dispatching action in a component function
vuex dispatching action in a component function

Time:05-28

I want to dispatch an action and get the values passed into an input. When i directly dispatch an action on a button like this:

 <button type="button" @click="store.dispatch("foundJobs", {
    nameInputValue: nameFilter.value, 
    locationInputValue: locationFilter.value, 
    contractCheckboxValue: contractFilter,
});">Search</button>

everything works perfectly fine. But when i want to make an outer function to make it more clean and readable, instead of getting values of an input it gives me an input element as an output:

const nameFilter = ref("");
const locationFilter = ref("");
const contractFilter = ref(false);

 <input type="text" placeholder="Filter by title, companies, expertise…"  ref="nameFilter"/>
 <input type="text" placeholder="Filter by location…" ref="locationFilter"/>
 <input type="checkbox" v-model="contractFilter" />

const searchResults = () => {
  store.dispatch("foundJobs", {
    nameInputValue: nameFilter.value, // console.log shows "input" element
    locationInputValue: locationFilter.value, // console.log shows "input" element
    contractCheckboxValue: contractFilter, // console.log shows "input" element
  });
};


 <button type="button" @click="searchResults">Search</button>

Why is that working like this?

CodePudding user response:

The difference between the code in script and template parts is that refs are unwrapped in templates.

It's a questionable practice to write the code in templates because this breaks the separation of concerns and makes a component less maintainable.

It should be:

 nameInputValue: nameFilter.value.value

The use of unref makes the intention more clear and emphasizes that value is accessed not on a ref but on some object:

nameInputValue: unref(nameFilter).value
  • Related