查阅官方文档: 接下来就来踩踩uniapp节点操作的坑吧
按照文档:写下如下代码,验证:
<template> <view class="content"> <view class="text-area" style="position: relative;"> <text class="title" style="position: absolute;" id="target">{{title}}</text> </view> </view> </template> <script> export default { data() { return { } }, onLoad() { //页面初始化执行,用户页面获取参数 this.getInfo() }, onReady() { //页面初次渲染完毕执行 }, methods: { getInfo() { // 注意:想要拿到元素实例,需要在实例已经挂载到页面上才可以 const query = uni.createSelectorQuery().in(this); query.select('#target').boundingClientRect(data => { console.log(data) }).exec(); } } } </script>查看效果: 拿到的值为空 ,why? 我们知道在vue中要想拿到dom元素,需要在dom元素挂载到页面上才可以,也就是在mounted()生命周期中,同理在uniapp中需要在页面生命周期中onReady() 或者组件周期mounted()内获取才有效 页面生命周期onLoad和onReady的区别:
onLoad() { //页面初始化执行,用户页面获取参数}, onReady() { //页面初次渲染完毕执行},把上述代码中的this.getInfo()放在onReady()生命周期中:
<template> <view class="content"> <view class="text-area" style="position: relative;"> <text class="title" style="position: absolute;" id="target">{{title}}</text> </view> </view> </template> <script> export default { data() { return { } }, onLoad() { //页面初始化执行,用户页面获取参数 }, onReady() { //页面初次渲染完毕执行 this.getInfo() }, methods: { getInfo() { // 注意:想要拿到元素实例,需要在实例已经挂载到页面上才可以 const query = uni.createSelectorQuery().in(this); query.select('#target').boundingClientRect(data => { console.log(data) }).exec(); } } } </script>效果:成功拿到该节点的集合信息,包括right,top,bottom,left,width,height