vue中父组件向子组件绑定事件的修饰符

1,270 阅读1分钟

vue中的修饰符.native

  • native是监听组件根元素的原生事件
  • 主要是给子组件上的根元素添加事件
  • 要注意的是仅在vue中有效

例子

  • 在父组件写sonBtn方法,对son组件标签进行绑定
  • 通过冒泡,做到修改son组件里的数据

父组件

<template>
  <div class="app">
    <button @click="appAtn">app点击</button>
    <!-- 为son根元素注册事件 -->
    <son ref="son" @click.native="sonBtn"></son>
  </div>
</template>

<script>
import son from "./components/son";
export default {
  data() {
    return {};
  },
  components: {
    son
  },
  methods: {
    appAtn() {
      this.$refs.son.msg = "app点击修改后的msg:" + parseInt(Math.random() * 10);
    },
    sonBtn() {
      this.$refs.son.msg = "son点击修改后的msg:" + parseInt(Math.random() * 10);
    }
  }
};
</script>

<style>
.app {
  width: 400px;
  height: 400px;
  background-color: skyblue;
}
</style>

子组件

<template>
  <div class="son">
    <button>son点击</button>
    <div>{{msg}}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      msg: "我是son的msg"
    };
  }
};
</script>

<style>
.son div {
  width: 200px;
  height: 200px;
  background-color: #f99;
}
</style>