1、Vue3中使用ref引用对象:
<script setup>
import {onMounted, ref} from 'vue'
//1.调用ref函数,生成一个ref对象
//2.通过ref标识,进行绑定
//3.通过ref对象.value可访问绑定的元素(必须渲染完成)
const myInput = ref(null)
onMounted(()=> {
myInput.value.focus();
});
</script>
<template>
<div>
<input ref="myInput" type="text" />
</div>
</template>2、Vue3中使用ref引用组件,子组件test-com.vue:
<script setup>
import {ref} from 'vue'
//默认情况下再<script setup>语法糖下组件内部的属性和方法是不开放给父组件访问的,
//可以通过defineExpose编译宏指定哪些属性和方法允许访问
const refName = ref('this is a demo')
defineExpose({
refName
})
</script>
<template>
<div>{{ refName }}</div>
</template>父组件使用:
<script setup>
import {onMounted, ref} from 'vue'
import TestCom from '@/components/test-com.vue'
//1.调用ref函数,生成一个ref对象
//2.通过ref标识,进行绑定
//3.通过ref对象.value可访问绑定的元素(必须渲染完成)
const testCom = ref(null)
onMounted(()=> {
console.log(testCom.value.refName)
});
</script>
<template>
<div>
<TestCom ref="testCom"></TestCom>
</div>
</template>3、Vue3中使用provide和inject函数顶层组件向底层组件传递属性和方法,App.vue:
<script setup>
import { ref,provide} from 'vue'
import TestCom from '@/components/test-com.vue'
//顶层组件向任意的底层组件传递数据和方法,实现跨层组件通信
//1.顶层组件通过provide函数提供数据,provide('key',顶层组件中的数据)
//2.底层组件通过inject函数获取数据,const message = inject('key')
const count = ref(100)
provide('count',count)
provide('changeCount',(newValue) => {
count.value = newValue
})
</script>
<template>
<div>
<TestCom></TestCom>
</div>
</template>test-com.vue
<script setup>
import {inject} from 'vue'
//默认情况下再<script setup>语法糖下组件内部的属性和方法是不开放给父组件访问的,
//可以通过defineExpose编译宏指定哪些属性和方法允许访问
const count = inject("count")
const changeCount = inject("changeCount")
const clickFunc = () => {
changeCount(200)
}
</script>
<template>
<div>{{ count }}</div>
<button @click="clickFunc">change</button>
</template>