Vue事件修饰符,阻止表单form里面的button的自动提交事件(prevent),阻止冒泡((stop self ))等……

70 阅读1分钟

具体代码和各个含义如下

image.png

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://unpkg.com/vue@next"></script>
    <style>
      .father {
        width: 500px;
        height: 500px;
        background-color: green;
      }
      .son {
        width: 200px;
        height: 200px;
        background-color: red;
      }
    </style>
  </head>
  <body>
    <div id="root"></div>
  </body>
  <script>
    const app = Vue.createApp({
      // 逻辑
      methods: {
        // 父选择器的逻辑
        fatherClick() {
          console.log("father is click");
        },
        // 子选择器的逻辑
        sonClick() {
          console.log("儿子被点击了");
        },
      },
      //   模板
      //   和阻止默认事件在@click后面加一个prevent类似,这里加的是stop
      // 子在父元素里面,点了后代选择器,也会触发父类,所以在子类里面加一个stop
      // 子里面@click.stop,意思是阻止冒泡,点击了自类,就只会触发子类
      template: `

<div class="father" v-on:click="fatherClick">
    <div class="son" v-on:click.stop="sonClick"></div>
    
    </div>
`,
    });

    // 处理在子类那里写.stop,也可以在父选择器那里写.self,意思是只有点击了,才会触发
    const vm = app.mount("#root");
    // > stop 和 self 的区别在于, stop 是阻止事件冒泡, self 是只有自身被点击时才会触发(只有自身才可以触发)
// > 如果只希望执行一次, 可以使用`@click.once="函数名"`
  </script>
</html>