当数据是 Vue 模板中的数组时,如何使数据具有反应性 [英] How to make data reactive when it's array in Vue Template

查看:20
本文介绍了当数据是 Vue 模板中的数组时,如何使数据具有反应性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<template>
  <button v-on:click="modify"> modify </button>
  <div v-model="lists">{{ lists[0] }}</div>
</template>

<script>
export default {

 methods: {
    modify: function() {
      console.log(this.lists)
      this.lists[0][0] = 2
      console.log(this.lists)
    },

  data: function () {
    return {
      lists: [[1,2,3],[2,3,3]]
    }
  }
}
</script>

模板中的数组似乎没有更新.但是日志控制台已经改变了.

The array at template does not seems to get updated. But the log console has changed.

当数据是数组时,如何使数据具有反应性?

How do you make a data reactive when it's an array?

实际情况:

Before clicking modify
<div v-model="lists">{{ lists[0] }}</div> # produce 1
After clicking modify
<div v-model="lists">{{ lists[0] }}</div> #produce 1

预期:

Before clicking  modify
<div v-model="lists">{{ lists[0] }}</div> # produce 1
After clicking modify
<div v-model="lists">{{ lists[0] }}</div> #produce 2

推荐答案

这是一个警告 在 Vue 中按索引更新数组时.试试这个.

This is a caveat when updating arrays by index in Vue. Try this.

this.lists[0].splice(0,1,2)

这篇关于当数据是 Vue 模板中的数组时,如何使数据具有反应性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆