Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind radio buttons to a vuex store?

Tags:

vue.js

vuex

I want to one-way bind the value of a set of radio buttons to my model and update the vuex store on change. Unfortunately this does not seem to be documented anywhere. Any help will be appreciated.

Two-way binding works as documented:

<input type="radio" name="info-source" value="1" id="info-source-1" v-model="infoSource">
<label for="info-source-1">TV</label>
<input type="radio" name="info-source" value="2" id="info-source-2" v-model="infoSource">
<label for="info-source-2">Social media</label>

However vuex starts complaining in this case Do not mutate vuex store state outside mutation handlers

like image 373
Kees de Kooter Avatar asked Aug 23 '17 13:08

Kees de Kooter


People also ask

What is the use of Mapstate in Vuex?

Mapping in Vuex enables you to bind any of the state's properties, like getters, mutations, actions, or state, to a computed property in a component and use data directly from the state. Although we can get the job done with this. $store.state.user.data.name , we can use a map helper to simplify it to this.

How do I use Vuex with vue3?

Adding Vuex to your Vue 3 Project js , create our store, and tell our app to use it. import { createApp } from "vue";import { createStore } from "vuex";// Create a new store instance or import from module. const store = createStore({ /* state, actions, mutations */});const app = createApp();app. use(store);app.

Is Vuex store reactive?

Vuex stores are reactive. When Vue components retrieve state from it, they will reactively and efficiently update if the store's state changes. You cannot directly mutate the store's state. The only way to change a store's state is by explicitly committing mutations.


1 Answers

This blogpost put me on the right track. The solution I came up with is this:

<input type="radio" name="info-source" value="1" 
       :checked="infoSource === 1" @change="updateInfoSource(1)">

With the updateInfoSource method committing to the store.

For a complete example look at the following post: How to bind radio buttons to a vuex store?

like image 127
Kees de Kooter Avatar answered Oct 18 '22 15:10

Kees de Kooter