Vue——获取组件:$parent & $root、$children & $refs、放大镜案例

168 阅读1分钟

parent & $root$children & $refs

注意:这些功能都是有劣势或危险的场景的,官方建议我们尽量避开它们。

 $root: 访问根组件vm对象,所有的子组件都可以将这个实例作为一个全局 store 来访问或使用,现在有更好的技术vuex代替。
 
 $parent:访问父组件对象,直接操作父组件的data数据,不需要再使用属性传值,但是容易出现渲染混乱之后只渲染一个的情况
 
 $children:访问子组件对象数组,不能保证顺序,也不是响应式的(因为在操作的过程中,组件可能会被销毁,也有可能会添加,所以顺序就会有变化)
          
 $refs:只会在组件渲染完成之后生效,并且它们不是响应式的。你应该避免在模板或计算属性中访问 $refs。(类似官方提供的DOM操作)
 
 //在组件或者原生元素绑定ref属性(类似于id):
 <myinput ref="myInput1"></myinput>
 <input ref="myInput2"></input>
 
 //在父组件中可以通过 this.$refs访问到它:
 methods: {
   focus: function () {
     this.$refs.myInput2.focus()
   }
 }
 
 

官网提示:

$refs 只会在组件渲染完成之后生效,并且它们不是响应式的。这仅作为一个用于直接操作子组件的“逃生舱”——你应该避免在模板或计算属性中访问 $refs

$refs是个对象,属性名就是绑定在模板中的ref的值(类似于id)

理解:

image.png

代码结果:

image.png

案例:放大镜

APP.vue文件:

<template>
  <div>
    <div id="box" ref="box">
			<div id="mask" ref="mask">
				
			</div>
		</div>
		<div id="show" ref="show">
			<img src="./1.png" ref="img">
		</div>
  </div>
</template>

<script>
export default {
  mounted(){
    // var box=document.querySelector("#box")
		// 	var  mask=document.querySelector("#mask")
		// 	var showimg=document.querySelector("#show img")
        var box=this.$refs.box
        var mask=this.$refs.mask
        var show=this.$refs.img
        box.onmouseover=function(){
				mask.style.display="block"
				// 实现鼠标拖拽效果
				box.onmousemove=function(e){
					// 求出鼠标在box内部的坐标
					// box到body的距离
					let x=box.offsetLeft
					// 移动时,鼠标到body的距离
					let x2=e.pageX
					// 鼠标在box内部的坐标
					let x3=x2-x
					let y=box.offsetTop
					let y2=e.pageY
					let y3=y2-y
					if(x3<35){
						x3=35
					}
					if(x3>315){
						x3=315
					}
					if(y3<35){
						y3=35
					}
					if(y3>311.5){
						y3=311.5
					}
					// -mask.offsetHeight/2:实现鼠标在小盒子的正中间
					mask.style.top=y3-mask.offsetHeight/2+"px"
					mask.style.left=x3-mask.offsetWidth/2+"px"
					
					show.style.top=-(y3-mask.offsetHeight/2)*(700/350)+"px"
					show.style.left=-(x3-mask.offsetLeft/2)*(700/350)+"px"
				}
			}
			// 鼠标移出大盒子,小盒子就隐藏起来
			box.onmouseout=function(el){
				mask.style.display="none"
				// 移除鼠标拖拽效果
				box.onmoousemove=null
			}
  }

};
</script>

<style lang="scss">
#box{
			/* 宽度与图片大小等比例 */
			width: 350px;
			height: 346.5px;
			background-image: url(./1.png);
			background-size: 100% 100%;
			position: relative;
		}
		#mask{
			width:70px ;
			height: 70px;
			/* 透明度 */
			background-color: rgba(255,215,0,0.5);
			/* 先将移动的盒子隐藏了 */
			display: none;
			/* 绝对定位是为了方便实现拖拽效果 */
			position: absolute;
		}
		#show{
			width: 350px;
			height: 350px;
			position: relative;
			left: 400px;
			top: -346.5px;
			overflow: hidden;
		
		}
		#show img{
			width: 700px;
			height: 693px;
			position: absolute;
			
		}
</style>

image.png