主页 > 区块链钱包 > [imtoken钱包客户端]Vue3通过ref操作Dom元素及hooks的使用方法

[imtoken钱包客户端]Vue3通过ref操作Dom元素及hooks的使用方法

admin 区块链钱包 2023年02月01日
import useWindwoResize from '../hooks/useWindowResize'; setup(){ const {width, height} = useWindwoResize() return{width,height} }

新建hooks文件夹在里面新建useWindowResize.js文件,内容如下:

<h1>屏幕尺寸:</h1> <div>宽度:{{ width }}</div> <div>高度:{{ height }}</div>

引入hooks中的js文件

<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页面:

父组件

关于Vue3通过ref操作Dom元素及hooks的使用方法的文章就介绍至此,更多相关Vue3通过ref操作Dom元素及hooks的使用方法内容请搜索编程宝库以前的文章,希望以后支持编程宝库!

setup() { const commer = ref(null) onMounted(()=>{ console.log(commer); console.log(commer.value); }) return { commer } }

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)比较像。

Suspense组件官网中有提到他是属于实验性功能:<Suspense>是一项实验性功能。它不一定会最终成为稳定功能,并且在稳定之前相关 API 也可能会发生变化。&l ...

Vue3通过ref操作Dom元素及hooks的使用方法 Vue3 ref获取DOM元素 <div ref="divBox">Hello</div> import {ref,onMounted} from 'vue' setup() { const divBox = ref(null); onMounted(()=>{ console.log(divBox.value); }) return{divBox} }

看这个例子:

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异步组件Suspense的使用方法详解JS 编程技术

<template> <div> <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>

子组件:

父组件:

父组件监听子组件中的元素

在父组件中的子组件里会打印一个proxy(实例),通过实例去获取里面的属性或者值

本文网络收集整理,不构成任何投资建议。转载请注明出处:https://www.lvsezhalan.org.cn/imqkl/971.html