zoukankan      html  css  js  c++  java
  • VueJS组件通过props自定义事件

    父组件是使用 props 传递数据给子组件,但如果子组件要把数据传递回去,就需要使用自定义事件!

    我们可以使用 v-on 绑定自定义事件, 每个 Vue 实例都实现了事件接口(Events interface),即:

    •     使用 $on(eventName) 监听事件
    •     使用 $emit(eventName) 触发事件


    另外,父组件可以在使用子组件的地方直接用 v-on 来监听子组件触发的事件。

    以下实例中子组件已经和它外部完全解耦了。它所做的只是触发一个父组件关心的内部事件。

    HTML

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>
    <script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
    </head>
    <body>
    <div id="app">
        <div id="counter-event-example">
          <p>{{ total }}</p>
          <button-counter v-on:increment="incrementTotal"></button-counter>
          <button-counter v-on:increment="incrementTotal"></button-counter>
        </div>
    </div>
    
    <script>
    Vue.component('button-counter', {
      template: '<button v-on:click="increment">{{ counter }}</button>',
      data: function () {
        return {
          counter: 0
        }
      },
      methods: {
        increment: function () {
          this.counter += 1
          this.$emit('increment')
        }
      },
    })
    new Vue({
      el: '#counter-event-example',
      data: {
        total: 0
      },
      methods: {
        incrementTotal: function () {
          this.total += 1
        }
      }
    })
    </script>
    </body>
    </html>

    效果如图:

  • 相关阅读:
    POJ 3669 Meteor Shower(bfs)
    MongoDB 分片的原理、搭建、应用
    Linux下Mongodb安装和启动配置
    目录操作
    一阶段第四次整理(关于滚动条监听的进一步解释)
    HTML DOM 节点介绍(nodeName,nodeValue,nodeType)
    ASP.NET 开发人员应该知道的8个网站
    Java 里快如闪电的线程间通讯
    php-多态
    Winform控件学习-TreeView
  • 原文地址:https://www.cnblogs.com/boonya/p/7093351.html
Copyright © 2011-2022 走看看