简体   繁体   中英

V-model on array of elements in Vue.js

I have the following

<el-row v-for="(position, index) in postForm.positions">
    <el-form-item label="Pages" :prop='"pages" + index'>
        <el-select v-model="postForm.positions[index].pages" v-bind:key="'page' + index" placeholder="Select Site Pages">
            <el-option v-for="page in sitePages" v-bind:key="page.id + index" :label="page.text" :value="page.id" />
        </el-select>
    </el-form-item>
    <el-form-item label="Categories" :prop='"categories" + index'>
        <el-select v-model="postForm.positions[index].categories" v-bind:key="'category' + index" placeholder="Select Categories">
            <el-option v-for="category in categories" v-bind:key="category.id + index" :label="category.translation.name" :value="category.id" />
        </el-select>
    </el-form-item>
    <el-form-item label="Position" prop='"position" + index'>
        <el-select v-model="postForm.positions[index].position" v-bind:key="'position' + index" placeholder="Select Banner Position">
            <el-option v-for="sitePosition in siteBannerPositions" v-bind:key="sitePosition.id + index" :label="sitePosition.text" :value="sitePosition.id" />
        </el-select>
    </el-form-item>
</el-row>

I expect each position row to have its own v-mode but when i change page in a row all other pages in other rows change as well as category and position.

I want each row to be independent from other rows.

I have this:

<el-form-item>
    <el-button type="danger" @click="addPositionRow">+</el-button>
</el-form-item>

And this is my addPositionRow method:

addPositionRow() {
  this.postForm.positions.push(new_position_row)
}

Thank you

Finally i found the solution. I will write it down so that it may help someone else ... I had this


new_position_row = {
        page: undefined,
        category_id: undefined,
        position: undefined
      }

And i was pushing this object into my postForm each time. So i was binding this object to every row just like the following:



  addPositionRow() {
      this.postForm.positions.push(new_position_row)
    }

What i needed to resolve the issue was to bind a new instance of new_position_row in every row just like this:


addPositionRow() {
  const new_position_row = {
    page: undefined,
    category_id: undefined,
    position: undefined
  }
  this.postForm.positions.push(new_position_row)
}

That's it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM