Pass the selected value: use vuex implementation method in the method
P粉218775965
2023-08-20 22:01:35
<p>I tried passing my selection value in FilterStatus method using Vuex but it is not passing the value of selection option to the method. </p>
<p>This is my component FilterStatus.vue, I use v-model to save the value of the option and use useStore to pass the status</p>
<pre class="brush:php;toolbar:false;"><template>
<div class="filter">
<select v-model="filter">
<option value="">All</option>
<option value="Alive">Alive</option>
<option value="Dead">Death</option>
<option value="unknown">Unknown</option>
</select>
</div>
</template>
<script>
import { useStore } from 'vuex'
export default {
setup() {
const store = useStore()
const filter = ((status) => {
store.dispatch('filterStatus', status)
})
return {
filter
}
}
}
</script>
<style>
</style></pre>
<p>In this part, I used Vuex and in actions I have my filterStatus method</p>
<pre class="brush:php;toolbar:false;">import { createStore } from 'vuex'
export default createStore({
state: {
characters: [],
charactersFilter: []
},
mutations: {
setCharacters(state, payload) {
state.characters = payload
},
setCharactersFilter(state, payload) {
state.charactersFilter = payload
}
},
actions: {
async getCharacters( {commit} ) {
try {
const res = await fetch('https://rickandmortyapi.com/api/character')
const data = await res.json()
commit('setCharacters', data.results)
commit('setCharactersFilter', data.results)
} catch (error) {
console.log(error)
}
},
filterStatus({commit, state}, status) {
const filter = state.characters.filter( (character) => {
return character.status.includes(status)
})
commit('setCharactersFilter', filter)
}
},
modules: {
}
})</pre>
<p>Thank you very much for your help</p>
v-model should be given a data variable, not a function. In Vue 3, you should also declare this variable using
ref
orreactive
to create reactive state, for example:Now,
filter
will save the value of the selected option when set to the selector's v-model. Then, the second thing you need to do is use an "on change" event listener to respond to changes in the selection, so that every time thefilter
is updated, you can commit it to your vuex store.