vue3基础

watch

监听一个值:

import {ref, watch} from "vue";
const count = ref(0)
watch(count,(newValue,oldValue)=>{
  console.log(newValue,oldValue)
},{
  immediate:true,
  deep:true
})

监听一个对象,如果修改一个对象的属性触发watch,需要添加deep


监听多个值: 任意一个值变化都会执行

import {ref, watch} from "vue";
const count = ref(0)
const name = ref("cc")

watch([count,name],([newCount,newName],[oldCount,oldName])=>{
  console.log(newCount,newName,oldCount,oldName)
})

精确监听对象的某个属性,,deep为true会监听对象所有属性,,有些时候只需要监听其中一个属性的变化:

import {ref, watch} from "vue";
const info = ref({name:"cc",age:20})

watch(()=>info.value.age,(newValue,oldValue)=>{
  console.log(newValue,oldValue)
})

deep属性一旦开启,就会执行递归遍历,有一定的性能损耗,绝大多数情况下,不开启deep,使用精确侦听

生命周期函数

连续多次调用钩子函数: 会依次执行

import {onBeforeMount, onMounted} from "vue";

 onMounted(()=>{
   console.log("mounted")
 })
onMounted(()=>{
  console.log("mounted222")
})
父子通信

父传子: defineProps()
子传父:defineEmits()


<script setup>
// 编译器宏函数
const props = defineProps({
  message:String,
  hehe:String
})

console.log(props)

// var emit = defineEmits(["get-message"])
var emit = defineEmits(["get-message"])
const getMessage = ()=>{
  emit("get-message","cc")
}
</script>

<template>
<div>son  --{{message}}</div>
  <div> {{ props.hehe}}</div>
  <button @click="getMessage">btn</button>
</template>
获取dom实例

ref引用组件实例,,因为默认情况下在setup里面,组件内部的属性和方法是不开放给父组件的,如果需要开放,需要在自组件中使用defineExpose()暴露出属性

const test = "123232"
defineExpose({
  test:test
})
跨层组件通信

provide提供变量和方法
inject 接收变量和方法:
底层组件可以修改顶层组件,, 使用顶层组件传递下来的函数

<script setup>
import father from "./components/father.vue"
import {provide, ref} from "vue";

const count = ref(0)
provide("key",count)

const add = ()=>{
  count.value++
}

provide("add",add)
</script>

<template>

<father></father>


</template>
<script setup>


import {inject} from "vue";

const message = inject("key")
const add =inject("add")
</script>

<template>
son -- {{message}}
  <button @click="add">add</button>
</template>

相关推荐

  1. vue3基础

    2024-06-19 09:42:02       22 阅读
  2. Vue3基础

    2024-06-19 09:42:02       21 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-19 09:42:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-19 09:42:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-19 09:42:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-19 09:42:02       20 阅读

热门阅读

  1. C++ 设计模式

    2024-06-19 09:42:02       8 阅读
  2. 19、架构-虚拟化容器

    2024-06-19 09:42:02       10 阅读
  3. python 数据清洗基础教程

    2024-06-19 09:42:02       7 阅读
  4. MongoDB基础知识

    2024-06-19 09:42:02       6 阅读
  5. 十三、数论基础

    2024-06-19 09:42:02       5 阅读
  6. Ruby 数据库访问 - DBI 教程

    2024-06-19 09:42:02       8 阅读
  7. 安卓交叉编译——ndk

    2024-06-19 09:42:02       10 阅读
  8. Swarm 集群管理

    2024-06-19 09:42:02       11 阅读
  9. PostgreSQL源码分析——创建用户

    2024-06-19 09:42:02       10 阅读