reactive函数

reactive函数

  • 作用: 定义一个对象类型的响应式数据(基本类型不要用它,要用ref函数)

  • 语法:const 代理对象= reactive(源对象)接收一个对象(或数组),返回一个代理对象(Proxy的实例对象,简称proxy对象)

  • reactive定义的响应式数据是“深层次的”。

  • 内部基于 ES6 的 Proxy 实现,通过代理对象操作源对象内部数据进行操作。

<template>
  <div class="about">
    <ul>
      <ol>{{obj.carName}}</ol>
      <li>{{obj.money}}</li>
      <li v-for="(item,index) in obj.carList" :key="index">
        车辆姓名:{{item.name}} <br>
        生成时间:{{item.age.startAge}} <br>
        结束时间:{{item.age.entAge}} <br>
      </li>
    </ul>
    <button @click="changgeCar">点击修改车辆</button>

    <hr>


    <ul>
      <ol>{{obj1.carName}}</ol>
      <li>{{obj1.money}}</li>
      <li v-for="(item,index) in obj1.carList" :key="index">
        车辆姓名:{{item.name}} <br>
        生成时间:{{item.age.startAge}} <br>
        结束时间:{{item.age.entAge}} <br>
      </li>
    </ul>
    <button @click="changgeCar1">点击修改车辆1</button>
  </div>
</template>
<script>
import { reactive, ref } from '_vue@3.2.33@vue'
export default {
  setup(){
    // 使用ref的
    let obj = ref({
      carName : '五菱宏光',
      money : '18W',
      carList:[
        {
          id:1,
          name:'MINI五菱',
          age:{
            startAge:2018,
            entAge:2020
          }
        }
      ]
    })
    function changgeCar(){
      console.log(obj.value)
      obj.value.carName = '宝马'
      obj.value.money = '30W'
      obj.value.carList[0].name = '宝马一号'
      obj.value.carList[0].age = {
        startAge:1018,
        entAge:1020
      }
    }

    //使用reactive  , 不需要写value
    let obj1 = reactive({
      carName : 'A-五菱宏光',
      money : 'A-18W',
      carList:[
        {
          id:1,
          name:'A-MINI五菱',
          age:{
            startAge:'A-2018',
            entAge:'A-2020'
          }
        }
      ]
    })
      function changgeCar1(){
        console.log(obj1)
        obj1.carName = '宝马'
        obj1.money = '30W'
        obj1.carList[0].name = '宝马一号'
        obj1.carList[0].age = {
          startAge:1018,
          entAge:1020
        }
    }
    return {obj,obj1,changgeCar,changgeCar1};
  }
}
</script>

 

posted @ 2022-05-16 19:06  杨建鑫  阅读(239)  评论(0编辑  收藏  举报