Vue3的setup注意事项

1、setup的执行时机

在beforeCreate之前执行一次,this是undefined

2、setup参数

props: 值为对象,包含:组件外部传递过来,且组件内部声明接收了的属性。

context: 上下文对象

  • attrs: 值为对象,包含:组件外部传递过来,但没有在props配置中声明的属性,相当于this.$attrs
  • slots: 收到的插槽内容,相当于this.$slots
  • emit: 分发自定义事件的函数,相当于this.$emit

3、计算属性

<script>
import {reactive, computed} from 'vue'
export default{
  name: 'Demo',
  setup() {
    let person = reactive({
      firstName: string;
      lastName: string;
    })
  }
  //直接利用person对象的响应式特性,添加fullName属性,并且是计算属性,
  //计算属性的简写(没有考虑计算属性被修改的情况)
  person.fullName = computed() => {
    return person.firstName + person.lastName
  }
  
  //计算属性完整版写法
  let fullName = computed() => {
    get(){
      return person.firstName+' '+person.lastName
    },
    set(value){
      const nameArr = value.split(" ")
      person.firstName = nameArr[0]
      person.lastName = nameArr[1]
    }
  }
  
  return {
    person  
  }
}
</scritp>

watch

<template>
  <p> {{sum}} </p>
  <button @click="sum+">点我加一</button>
</template>
<script>
import {reactive, computed} from 'vue'
export default{
  name: 'Demo',
  /*
  watch: {
    //简写
    sum(newValue, oldValue) {
      console.log("sum 新值: " , newValue ,"sum 旧值: ", oldValue)
    }
    //完全写法
    sum: {
      immediate: true,
      deep: true
      handler(newValue, oldValue) {
        console.log("sum 新值: " , newValue ,"sum 旧值: ", oldValue)
      }
    }
  },
  */  
  setup() {
    let sum = ref(0)
    let msg = ref("你好啊")
    
    let person = reactive({
      name: '张三',
      age: 19,
      job: {
        type: '程序员',
        salary: '30k'
      }  
    })

    //vue3 情况一,监听ref所定义的
    watch(sum, (newValue, oldValue) => {
      console.log("sum变了", newValue, " ",oldValue)
    }
    //vue3 情况二、监听ref所定义的多个响应式数据【数组】
    watch([sum, msg],newValue, oldValue) => {
      console.log("监听数据变了", newValue, " ",oldValue)
    }, {
      immediate: true,
      deep: true//deep有坑
    })

    //vue3 情况三,监听reactive所定义的响应式对象的全部属性, 
    //1、如果用watch监听reactive定义的对象,无法获取正确的oldValue,永远获取的是最新对象。
    //2、监视reactive对象强制开启了深度监视
    watch(person, (newValue, oldValue) => {
      console.log("person变了", newValue, " ",oldValue)
    }
    //vue3 情况四, 监视reactive定义的对象的单个属性,使用函数,不能想监听ref,reactive一样
    watch(() => (person.age ,(newValue, oldValue) => {
      console.log("person.age 变化了", newValue, oldValue)
    })
    //vue3 情况五,监视reactive所定义的一个响应式数据的某些属性
    watch([() => person.name, () => person.age], (newValue, oldValue) => {
       console.log("person.age 或person.name 变化了", newValue, oldValue)
    })
    //特殊情况,reactive对象中的,属性依然是对象
    watch(() => (person.job,(newValue, oldValue) => {
      console.log("person.job变化了", newValue, oldValue)
    },{deep:true})
    return {
      sum,
      msg,
      person
    }
  }

}
</scritp>
posted @ 2022-08-10 01:16  wjwdive  阅读(182)  评论(0编辑  收藏  举报