Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of v-model and v-for with array in Vuex state

I'm building the tabs for a tabbed interface, in which the user can change the titles of the tabs. What I'd like to do is something like this:

Markup:

<div class="tabs" v-for="(tab, tabIndex) in tabs" :key="tab.id" >
  <input type="text" v-model:value="tabs(tabIndex)">
</div>

Computed property:

computed: {
  scenes2: {
    get(tabIndex){
      return this.$store.state.tabs[tabIndex].title
    },
    set(value, tabIndex){
      this.$store.dispatch('setTabTitle', {value: value, tabIndex: tabIndex} )
    },
  },
},

This doesn't work, of course. What is the proper way to use v-model here so that I can correlate the v-model with the relevant index on the tabs array in the Vuex state?

like image 512
drenl Avatar asked Apr 22 '18 15:04

drenl


People also ask

What is V-for in Vue?

v-for directive is a Vue. js directive used to loop over a data usually an array or object. First, we will create a div element with id as app and let's apply the v-for directive to an element with data. Now we will create this data by initializing a Vue instance with the data attribute containing the value.

What is key in V-for?

The purpose of this key attribute is to give "a hint for Vue's virtual DOM algorithm to identify VNodes when diffing the new list of nodes against the old list" (from Vue. js Docs). Essentially, it helps Vue identify what's changed and what hasn't.

What does V-model do?

v-model is a common directive used in almost every Vue application. It's typically used to enable two-way data binding on form elements and works perfectly with input , checkbox , select , textarea and radio .

What is Vuex strict mode?

In strict mode, whenever Vuex state is mutated outside of mutation handlers, an error will be thrown. This ensures that all state mutations can be explicitly tracked by debugging tools.


1 Answers

I wouldn't use computed properties with arrays and objects.

 <div class="tabs" v-for="(tab, tabIndex) in $store.state.tabs" :key="tab.id">
   <input type="text" :value="tab.title" @input="e => updateTabTitle(tabIndex, e)">
 </div>

methods: {
  updateTabTitle(tabIndex, event) {
    this.$store.dispatch('setTabTitle', {value: event.target.value, tabIndex} )
  }
}
like image 92
Renaud Avatar answered Oct 19 '22 21:10

Renaud