0
点赞
收藏
分享

微信扫一扫

[vue3.x]ref的使用

云竹文斋 2022-04-15 阅读 54
前端

[vue3.x]ref的使用

普通的应用

DOM 元素将在初始渲染后分配给 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 条评论