vue3学习之对象和数组的响应式绑定

我爱海鲸 2023-01-10 16:45:57 前端

简介对象和数组

链接上一篇文章:vue3学习之更近一步reactive

在vue2中我们知道了对于新增的数组和对象不是一个响应式的变量,当然我们可以通过$set将其设置为一个响应式的对象

那vue3中我们怎么做呢?少废话上源码

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <h1>{{count}}</h1>
    <h1>{{double}}</h1>
    <ul>
      <li v-for="number in numbers" :key="number">
        <h1>{{number}}</h1>
      </li>
    </ul>
    <h1>{{person.name}}</h1>
    <button @click="increase">赞+1</button><br/>
  </div>
</template>

<script lang="ts">
  // 响应式对象引入,计算函数引入
import { ref,computed,reactive,toRefs } from 'vue'

interface DataProps {
  count: number;
  double: number;
  increase: () => void;
  numbers: Array<number>,
  person: {name ? :string}
}

export default{
  name: 'App',
  setup() {
    const data: DataProps  = reactive({
      count: 0,
      increase: () => { data.count++},
      double: computed(() => data.count * 2),
      numbers: [0,1,2],
      person: {}
    })
    data.numbers[0] = 5;
    data.person.name = 'haijin';
    const refData = toRefs(data)
    return {
      ...refData
    }
  }
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

效果:

 

你好:我的2025