【问题标题】:Vue slot-scope with v-for, data changed but not re-rendered带有 v-for 的 Vue slot-scope,数据已更改但未重新渲染
【发布时间】:2018-09-11 11:56:12
【问题描述】:

我在学习vuejs2的时候有个问题

我用 slot-scope && v-for 做了一个例子,但它有一个我无法理解的错误。

这里是示例代码 https://jsfiddle.net/eywraw8t/6839/

app.vue

<template id="list-template">
  <div>
    <ul>
      <slot name="row" v-for="item in list" v-bind=item />
    </ul>
  </div>
</template>

<div id="app">
  <list-component :list="list">
    <li slot="row" slot-scope="item">
      <a href="#" @click.prevent="h(item)">{{item.name}}</a>
    </li>
  </list-component>
</div>
Vue.component('list-component', {
  template: '#list-template',
   props: {
      list: {
        type: Array
      }
   }
});

new Vue({
  el: '#app',
  data () {
    return {
        list: [
        {id: 1, name: 'Apple'},
        {id: 2, name: 'Banana'},
        {id: 3, name: 'Cherry'},
        {id: 4, name: 'Durian'},
        {id: 5, name: 'Eggplant'}
      ]
    }
  },
  methods: {
    h (item) {
      item.name = item.name.toUpperCase()
      console.log('Changed!')
      console.log(item)
    }
  }
});

奇怪的是,方法 'h' 被触发,然后控制台说 'Changed!'并且数据也发生了变化,但是视图没有重新渲染。

我错过了什么?我认为插槽范围的对象数据没有引用原始对象数据。

如何修改原始数据?

感谢您阅读此问题。

【问题讨论】:

  • 你必须从组件中监听点击事件

标签: vue.js vuejs2 vue-component


【解决方案1】:

您直接尝试修改数组中某个项目的值。由于某些limitations vue 无法检测到此类数组修改。

所以更新您的代码以使用vm.$set() 对数组项进行更改。

methods: {
    h (item) {
      let i = this.items.findIndex((it) => it.id === item.id);
      this.$set(this.list, i, {...item, name: item.name.toUpperCase()});
    console.log(item.id)
  }

这里是你pdated fiddle

【讨论】:

  • 谢谢!是否可以在没有搜索索引的情况下修改数据?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-10
  • 2020-12-16
  • 1970-01-01
  • 2021-04-16
  • 1970-01-01
  • 2018-12-04
  • 2019-09-22
相关资源
最近更新 更多