Vue3.x初始化项目(包含配置好的eslint)以及Proxy与Reflect例子、watch、toRef、toRefs

- 安装

npm install -g @vue/cli
//检查版本
vue --version
//初始化项目
vue create vue-test

- Proxy、Reflect

  • 通过window的Proxy对象实现代理,因为目的是要知道数据何时变化,再变化之后要去更改视图随之变化,再Proxy中使用了Reflect(反射),通俗来理解和obj.a没有什么区别,但是对于框架封装来说,他的返回值是Boolean类型,比起Object.defineProperty不断的try…catch更加方便,值得注意的是新增属性与修改属性都会触发set,set被触发,自然会有一系列操作去更新视图。
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    const person = {
      name:'hhh'
    }
    let p = new Proxy(person,{
        get(target, propName){
            console.log('读取了数据')
            return Reflect.get(target, propName)
        },
        set(target, propName, newValue){
            console.log('修改/新增更新视图')
            Reflect.set(target, propName, newValue)
        },
        deleteProperty(target, propName){
            console.log('删除更新视图')
            // 值得注意 如果你试图删除的属性不存在,那么delete将不会起任何作用,但仍会返回true
            return delete Reflect.deleteProperty(target, propName)
        }
    })
    console.log(p)
  </script>
</body>
</html>
  • watch系列
  • 监视ref所定义的响应式数据
<template>
  <span>{{ sum }}</span>
  <button @click="onChangeNum">点我+1</button>
  <br />
  <div>
    <span>{{ msg }}</span>
    <button @click="msg += '!'">点我+1</button>
  </div>
</template>

<script>
import { reactive, ref, watch } from 'vue';
export default {
  name: 'App',
  setup() {
    let sum = ref(0);
    let msg = ref('hh');
    function onChangeNum() {
      sum.value++;
    }
    // 监视ref所定义的响应式数据 (配置项为第二个参数,{})
    watch(
      sum,
      (newValue, oldValue) => {
        console.log(newValue); // 0
        console.log(oldValue); // 1
      },
      { immediate: true },
    );
    // 监视ref所定义多个的响应式数据(多个数据在数组中,谁变化谁改变)
    watch(
      [sum, msg],
      (newValue, oldValue) => {
        console.log(newValue); // [1, "hh"]
        console.log(oldValue); // [0, "hh"]
      },
      { immediate: true },
    );
    return {
      sum,
      msg,
      onChangeNum,
    };
  },
};
</script>
  • 监视reative所定义的响应式数据
  • 直接监视reactive对象(此处同理ref对象写法,因为ref对于对象形式,内部依然使用了reactive,所以结果一致,唯一有区别的的就是watch时需要监视sum.value || msg.value)
watch(
    sum.value,
     (newValue, oldValue) => {
       console.log(newValue); // immediate 初次正常 0         // 不加immediate  初次 1
       console.log(oldValue); // undefined                   //  1
     },
     { immediate: true },
   );
<template>
  <span>{{ sum.count }}</span>
  <button @click="onChangeNum">点我+1</button>
  <br />
  <div>
    <span>{{ msg }}</span>
    <button @click="msg.text += '!'">点我+1</button>
  </div>
</template>

<script>
import { reactive, ref, watch } from 'vue';
export default {
  name: 'App',
  setup() {
    let sum = reactive({
      count: 0,
    });
    let msg = reactive({
      text: 'hhhh',
    });
    function onChangeNum() {
      sum.count++;
    }
    // 监视reactive所定义的响应式数据 (配置项为第二个参数,{})
    watch(sum, (newValue, oldValue) => {
      console.log(newValue); // immediate 初次正常 0         // 不加immediate  初次 1
      console.log(oldValue); // undefined                   //  1
    });
    // 监视reactive所定义多个的响应式数据(多个数据在数组中)
    watch([sum, msg], (newValue, oldValue) => {
      console.log(newValue); // immediate 初次正常 [0, "hhhh"]   // 不加immediate  初次 [1, 'hhhh']
      console.log(oldValue); // []                          //  [1, 'hhhh']
    });
    return {
      sum,
      msg,
      onChangeNum,
    };
  },
};
</script>

-监视reactive定义的数据,无论嵌套多深,默认开启了deep:true

<div>
  <span>{{ msg }}</span>
  <button @click="msg.job.text += '!'">点我+1</button>
</div>
watch(
   msg,
   (newValue, oldValue) => {
     console.log(newValue);
     console.log(oldValue); 
   },
   { immediate: true },
 );
  • 监视reactive定义的某一个属性应写成函数形式(此时oldValue好用了)
//冗余代码同上
watch(
    ()=> msg.job.text,
    (newValue, oldValue) => {
      console.log(newValue); //xxx=>xxx!
      console.log(oldValue); //undefined=>xxx
    },
    { immediate: true },
  );
  • 监视reactive定义的某些个属性应写成数组嵌套函数形式(此时oldValue好用了)
watch(
      [() => msg.job.text, () => msg.text],
      (newValue, oldValue) => {
        console.log(newValue); // 初次 ["xxx", "hhhh"] => ["xxx!", "hhhh"]
        console.log(oldValue); // [] => ["xxx", "hhhh"]
      },
      { immediate: true },
    );
  • 监视reactive定义的某个数据(对象形式),此时直接()=> msg.job是检测不到的,数据变化了,但是检测不到,此时应开启deep:true(此时oldValue不好用了)
let msg = reactive({
   text:'hhhh',
   job: {
     text: 'xxx',
   },
 });
watch(
    () => msg.job,
    (newValue, oldValue) => {
      console.log(newValue); // 初次 {text: "xxx"} => {text: "xxx!"}
      console.log(oldValue); // undefined => {text: "xxx!"}
    },
    { immediate: true, deep: true },
  );
  • watchEffect 初始化执行一次,相当于immediate: true,内部响应式数据变化,重新执行,注重过程,computed注重结果,这里他的x值是改变后值,
let msg = reactive({
    text: 'hhhh',
    job: {
      text: 'xxx',
      arr: [1, 2],
    },
  });
watchEffect(() => {
    const x = msg.text; // xxx  xxx! xxx!!
    console.log('执行了');
  });
  • toRef

在这里插入图片描述
此时objectToRef 是一个RefImpl对象,其中value属性为msg中的text值

setup() {
  let sum = ref({
    count: 0,
  });
  let msg = reactive({
    text: 'hhhh',
    job: {
      text: 'xxx',
      arr: [1, 2],
    },
  });
  function onChangeNum() {
    sum.value.count++;
  }
  console.log(objectToRef);
  return {
    text: toRef(msg, 'text'),
    jobText: toRef(msg.job, 'text'),
    sum,
    msg,
    onChangeNum,
  };
},
  • toRefs 直接返回对象形式,通过…扩展运算符直接return出去,内部无论多深都是proxy对象

在这里插入图片描述
在这里插入图片描述

setup() {
  let sum = ref({
    count: 0,
  });
  let msg = reactive({
    text: 'hhhh',
    job: {
      text: 'xxx',
      arr: [1, 2],
    },
  });
  function onChangeNum() {
    sum.value.count++;
  }
  const objectToRef = toRefs(msg);
  console.log(objectToRef);
  return {
    // text: toRef(msg, 'text'),
    // jobText: toRef(msg.job, 'text'),
    ...objectToRef,
    sum,
    msg,
    onChangeNum,
 };
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值