欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > vue3基础

vue3基础

2025/4/21 22:28:10 来源:https://blog.csdn.net/qq_36022463/article/details/139778732  浏览:    关键词: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>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词