vue3 中 ref 和 reative 值为数组时如何重新赋值?

6,132 阅读1分钟

vue3 中 ref 和 reative 值为数组时如何重新赋值?

在vue3中我们经常使用 ref 或者 reactive 定义数组数据 当我们需要清空数组重新赋值时该怎么做呢?

通常我们会直接将变量赋值为空数组或新数组,如以下三种情况

const state = reactive<any>({
  source: [
    ['1月', 43.3],
    ['2月', 83.1],
    ['3月', 39.1],
    ['4月', 72.4],
    ['5月', 72.4]
  ]
})
const source = ref<any>([
  ['1月', 43.3],
  ['2月', 83.1],
  ['3月', 39.1],
  ['4月', 72.4],
  ['5月', 72.4]
])
const sourceState = reactive<any>([
  ['1月', 43.3],
  ['2月', 83.1],
  ['3月', 39.1],
  ['4月', 72.4],
  ['5月', 72.4]
])

直接简单粗暴的使用 变量名 = 新数组 是不行的, 会失去响应, 原因是啥什么呢?

正确的处理姿势: 使用 splice

// 场景1: ref([])
setInterval(() => {
  source.value.splice(0, state.source.lenth)
  source.value.push(
    ...[
      ['1月', Math.floor(43.3 * Math.random() * 10)],
      ['2月', Math.floor(43.3 * Math.random() * 10)],
      ['3月', Math.floor(43.3 * Math.random() * 10)],
      ['4月', Math.floor(43.3 * Math.random() * 10)],
      ['5月', Math.floor(43.3 * Math.random() * 10)]
    ]
  )
}, 3000)
// 场景2: reactive({state:[]})
setInterval(() => {
  state.source.splice(0, state.source.lenth)
  state.source.push(
    ...[
      ['1月', Math.floor(43.3 * Math.random() * 10)],
      ['2月', Math.floor(43.3 * Math.random() * 10)],
      ['3月', Math.floor(43.3 * Math.random() * 10)],
      ['4月', Math.floor(43.3 * Math.random() * 10)],
      ['5月', Math.floor(43.3 * Math.random() * 10)]
    ]
  )
}, 3000)

// 场景2: reactive([])
setInterval(() => {
  sourceState.splice(0, state.source.lenth)
  sourceState.push(
    ...[
      ['1月', Math.floor(43.3 * Math.random() * 10)],
      ['2月', Math.floor(43.3 * Math.random() * 10)],
      ['3月', Math.floor(43.3 * Math.random() * 10)],
      ['4月', Math.floor(43.3 * Math.random() * 10)],
      ['5月', Math.floor(43.3 * Math.random() * 10)]
    ]
  )
}, 3000)

应用场景: 动态改变Echarts的值

2023-07-04 14.59.30