vue中把一个事件绑定到子组件上


官网上是这样描述的

你可能有很多次想要在一个组件的根元素上直接监听一个原生事件。这时,你可以使用 v-on的 .native 修饰符

父组件App.vue

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <HelloWorld @click="outClick"/>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'app',
  components: {
    HelloWorld
  },
  methods: {
      outClick (){
          alert('我是父组件的方法')
      }
  }
}
</script>

子组件HelloWord.vue

<template>
  <div class="hello">
    <h1>HelloWorld</h1>
    <el-button type="primary">点我</el-button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld'

}
</script>

这时我们点击子组件的按钮是没有反应的,如果把父组件修改如下:

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <HelloWorld @click.native="outClick"/>     <!--在单击事件上添加.native-->
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'app',
  components: {
    HelloWorld
  },
  methods: {
      outClick (){
          alert('我是父组件的方法')
      }
  }
}
</script>

这时我们单击按钮,效果如下:

总结:其实就是把一个单击事件从父组件传递给子组件






免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM