Vue3学习日记(day5)

接下来我们继续探讨文档


event对象

在Vue.js中,$event变量或箭头函数中的event参数用于捕获原始的DOM事件对象。这个对象包含了所有与特定事件相关的信息,比如鼠标点击的位置、键盘按键的键码、触摸事件的触摸点等。

当你在事件处理器中需要做一些基于事件本身的处理时,如阻止默认行为(event.preventDefault())、停止事件传播(event.stopPropagation())、检查事件的详细信息等,就需要使用这个事件对象。

如果不传递event,你将无法访问这些功能。例如,如果你有一个表单提交按钮,你可能希望在警告用户之前阻止表单的默认提交行为。如果没有event参数,你就不能调用preventDefault(),这可能会导致页面刷新,即使你正在尝试警告用户。

<template>
  <form @submit="onSubmit">
    <input type="text" placeholder="Type something...">
    <button>Submit</button>
  </form>
</template>
export default {
  methods: {
    onSubmit(event) {
      event.preventDefault(); // 阻止表单的默认提交行为
      console.log('Form submitted');
      console.log('Input value:', document.querySelector('input').value);
    }
  }
}

事件修饰符

对于子元素父元素有重叠风险的:

1. .stop

假设你有一个父元素和一个子元素,当你点击子元素时,你希望只触发子元素的事件处理器,而不触发父元素的处理器。

<div id="parent" @click="logParentClick">
2  Parent element
3  <button id="child" @click.stop="logChildClick">Click me!</button>
4</div>
new Vue({
  el: '#app',
  methods: {
    logParentClick() {
      console.log('Parent clicked');
    },
    logChildClick() {
      console.log('Child clicked');
    }
  }
});

在这个例子中,当你点击按钮时,只会输出 "Child clicked",而不会输出 "Parent clicked"。这是因为.stop修饰符阻止了点击事件从子元素传递到父元素。

2. .prevent

假设你有一个表单,当用户提交表单时,你不希望页面刷新,而是显示一条消息。

<form @submit.prevent="logFormSubmit">
  <input type="text" placeholder="Enter your name">
  <button type="submit">Submit</button>
</form>
new Vue({
  el: '#app',
  methods: {
    logFormSubmit() {
      console.log('Form submitted');
    }
  }
});

在这个例子中,当你提交表单时,页面不会刷新,而是输出 "Form submitted" 到控制台。这是因为.prevent修饰符阻止了表单的默认提交行为。

3. .self

假设你有一个父元素和一个子元素,当你点击子元素时,你希望事件处理器只在点击父元素本身时才被触发。

<div id="parent" @click.self="logParentClick">
  Parent element
  <button id="child" @click="logChildClick">Click me!</button>
</div>
new Vue({
  el: '#app',
  methods: {
    logParentClick() {
      console.log('Parent clicked');
    },
    logChildClick() {
      console.log('Child clicked');
    }
  }
});

在这个例子中,当你点击按钮时,只会输出 "Child clicked",而不会输出 "Parent clicked"。这是因为.self修饰符确保事件处理器只在点击父元素本身时才被触发。


透传值

(这个我不是特别了解,所以做了案例)

子组件
<script setup>
import { defineProps } from "vue";

const props = defineProps({
  buttonText: String,
  customClass: String,
});
</script>

<template>
  <button :class="[customClass, 'base-button']">
    {{ buttonText }}
  </button>
</template>

<style scoped>
.base-button {
  background-color: red;
}
</style>
父组件
<script setup>
import HelloWorld from "./components/HelloWorld.vue";
</script>

<template>
  <HelloWorld
    :buttonText="'传递'"
    :customClass="'large-button'"
  ></HelloWorld>
</template>

<style scoped>
.large-button {
  font-size: 22px;
}
</style>

效果:

成功传递

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值