Vue3通过ref操作Dom元素及hooks的使用方法
Nanchen_42 人气:0Vue3 ref获取DOM元素
<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"> <h1>This is an about page</h1> <com ref="commer"></com> <h3>通过ref用父组件接收子组件中的宽和高:<span>{{numWidht}} {{numHeight}}</span></h3> </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> <h1>屏幕尺寸:</h1> <h1>宽度:{{width}}</h1> <h1>高度:{{height}}</h1> </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
在vue3中的hooks其实就是函数的写法,就是将文件的一些单独功能的js代码进行抽离出来,放到单独的js文件中。这样其实和我们在vue2中学的混入(mixin)比较像。
父组件
<h1>屏幕尺寸:</h1> <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;
加载全部内容