[vue3.x]ref的使用

[vue3.x]ref的使用

普通的应用

DOM 元素将在初始渲染后分配给 ref

因为 ref 本身是作为渲染函数的结果而创建的,在初始渲染时你不能访问它们——它们还不存在!

表单的主动提交

场景描述,将form表单设为组件,在父组件中,通过点击按钮,弹框modal 显示表单,点击modal的时候提交表单,因此需要代码控制点击modal提交按钮的时候提交form表单

form组件
self-form.vue

<a-form ref="formRef">
</a-form>
setup(){
const formRef = ref();
    const checkForm = () => {
      formRef.value
        .validate()
        .then((res) => {
          console.info("submit valid success");
          emit("mysub", form);//这与父组件的名称需要一致 mysub
        })
        .catch((error) => {
          if (undefined != error.errorFields && error.errorFields.length > 0) {
            console.error("validate faild......................", error);
          } else {
            console.error("catch excute.......", error);
          }
        });
    };
return {
formRef,
checkForm
}
}

父组件

<a-modal @ok="confirmMoal">
<self-form ref="submitForm" @mysub="addOrEdit"></self-form>
</a-modal>
setup(){
const submitForm = ref();
    const valid = () => {//check the form valid rule
 		if (null !=submitForm.value) {
			submitForm.value.checkForm();
		}
    };

const addOrEdit=()=>{
//submit form
}
return {
submitForm,
confirmMoal,
valid
}
}

注意对应的名称

v-for循环中对ref的应用

<template v-for="(item,index) in photos" v-bind:key="index">
<router-link 
          class="bamboo-photo"
          :ref="handleBox"
          :to="item.path"
          @mousemove="e=>move(e,index)"
          @mouseleave="e=>leave(index)"
          @mouseover="e=>over(index)"
        >
          <div class="reflection" :ref="handleRefl"></div>
          <div class="element bg">
            <!-- <div class="number">28</div> -->
            <div class="symbol">{{item.name}}</div>
            <!-- <div class="details">Nickel<br />58.6934</div> -->
          </div>
        </router-link>
</template>
setup(){
	const box=[];
        	const refl=[];
  	const handleBox=(el)=>{
      		box.push(el);
    	}
   	 const handleRefl=(el)=>{
     		 refl.push(el);
    	}
//设置值
const over = (index) => {
     	 //位于指定元素上方
      	refl[index].style.opacity = 1;
       };
       const leave = (index) => {
     	//离开指定元素
       	box[index].$el.style.transform = `perspective(500px) scale(1)`;
     	 refl[index].style.opacity = 0;
      };
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三知之灵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值