这篇文章主要介绍了Vue3通过ref操作Dom元素及hooks的使用方法是什么的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Vue3通过ref操作Dom元素及hooks的使用方法是什么文章都会有所收获,下面我们一起来看看吧。
<div ref="divBox">Hello</div>
import {ref,onMounted} from 'vue'
setup() {
const divBox = ref(null);
onMounted(()=>{
console.log(divBox.value);
})
return{divBox}
}
在父组件中的子组件里会打印一个proxy(实例),通过实例去获取里面的属性或者值
setup() {
const commer = ref(null)
onMounted(()=>{
console.log(commer);
console.log(commer.value);
})
return {
commer
}
}
看这个例子:
父组件:
<template>
<div class="about">
<h2>This is an about page</h2>
<com ref="commer"></com>
<h4>通过ref用父组件接收子组件中的宽和高:<span>{{numWidht}} {{numHeight}}</span></h4>
</div>
</template>
<script>
import com from '../components/com.vue'
import {ref,onMounted} from 'vue'
export default {
components: {
com
},
setup() {
const commer = ref(null)
const numWidht = ref(0);
const numHeight = ref(0)
onMounted(()=>{
numWidht.value =commer.value.width
numHeight.value =commer.value.height
})
return {
commer,numWidht,numHeight
}
}
}
</script>
子组件:
<template>
<h2>屏幕尺寸:</h2>
<h2>宽度:{{width}}</h2>
<h2>高度:{{height}}</h2>
</template>
<script>
// import { ref,onMounted } from 'vue';
import useWindwoResize from '../hooks/useWindowResize'
export default {
setup(){
const {width, height} = useWindwoResize()
return{width,height}
}
};
</script>
<style lang="scss" scoped>
</style>
hooks页面:
import {onMounted, onUnmounted, ref} from 'vue';
function useWindowResize(){
const width = ref(0)
const height = ref(0)
function onResize(){
width.value = window.innerWidth
height.value = window.innerHeight
}
onMounted(()=>{
window.addEventListener("resize",onResize);
onResize();
})
onUnmounted(()=>{
window.removeEventListener('resize',onResize);
})
return{
width,
height
}
}
export default useWindowResize;
在vue3中的hooks其实就是函数的写法,就是将文件的一些单独功能的js代码进行抽离出来,放到单独的js文件中。这样其实和我们在vue2中学的混入(mixin)比较像。
父组件
<h2>屏幕尺寸:</h2>
<div>宽度:{{ width }}</div>
<div>高度:{{ height }}</div>
引入hooks中的js文件
import useWindwoResize from '../hooks/useWindowResize';
setup(){
const {width, height} = useWindwoResize()
return{width,height}
}
新建hooks文件夹在里面新建useWindowResize.js文件,内容如下:
import {onMounted, onUnmounted, ref} from 'vue';
function useWindowResize(){
const width = ref(0)
const height = ref(0)
function onResize(){
width.value = window.innerWidth
height.value = window.innerHeight
}
onMounted(()=>{
window.addEventListener("resize",onResize);
onResize();
})
onUnmounted(()=>{
window.removeEventListener('resize',onResize);
})
return{
width,
height
}
}
export default useWindowResize;
关于“Vue3通过ref操作Dom元素及hooks的使用方法是什么”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“Vue3通过ref操作Dom元素及hooks的使用方法是什么”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。