美文网首页
Vue父子组件通信之$emit(基于vue2.5,ES6)

Vue父子组件通信之$emit(基于vue2.5,ES6)

作者: 兔子不打地鼠打代码 | 来源:发表于2018-06-07 21:37 被阅读285次

    一、$emit的作用

    在Vue中,父组件监听子组件触发的事件,需要在子组件用使用 $emit 触发,在父组件中使用 v-on: / @ 自定义事件监听。

    二、有几点必须非常注意:

    1、 vm.$emit( eventName, […args] ) 可以有两个参数;第一个参数必填,触发当前实例上的函数;第二个参数选填,是向函数传递的数据。

    2、在vue中,事件名不存在自动化的大小写转换,触发事件名需要完全匹配监听这个事件所用的名称(驼峰就必须驼峰,短横线就必须短横线。)

    3、父组件监听子组件触发的事件,不能用$on侦听子组件抛出的事件,而必须在模板里直接用v-on绑定子组件的事件。

    三、现在我们一起来看看个例子吧(基于 vue: 2.5.2,ES2015)

    【父组件】

    <template>
      <div>
        <magic-eight-ball  @give-advice="showAdvice">
        </magic-eight-ball>
      </div>
    </template>
    
    <script>
    import MagicEightBall from "../components/level2"
    
    export default {
      methods:{
        showAdvice(advice){
          alert(advice)
        },
      },
      components:{
        MagicEightBall,
      },}
    </script>
    

    【子组件】

    <template>
      <button @click="giveAdvice">
        click me for random alert
      </button>
    </template>
    
    <script>
      export default {
        data () {
          return {
            possibleAdvice:['num1','numb2','number3']}
        },
        methods:{
          giveAdvice(){
            let randomAdviceIndex = Math.floor(Math.random()
              *this.possibleAdvice.length);
            this.$emit('give-advice',
               this.possibleAdvice[randomAdviceIndex])
          }
        }
      }
    </script>
    

    四、解析代码

    • 1、在子组件的按钮中绑定click事件giveAdvice
      定义数据possibleAdvice的值;

    • 2、在子组件中定义giveAdvice()函数;

    • 3、将子组件 'MagicEightBall' 引入父组件,并在<magic-eight-ball>中绑定函数showAdvice,另命名为give-advice;

    • 4、在父组件中定义 shouAdvice函数,作用是弹提示框。

    • 5、在子组件中,将this.$emit添加到giveAdvice的最后一行,作用是触发父组件中的give-advice事件,并将randomAdviceIndex的值传给事件give-advice

    五、最后的呈现效果

    点击按钮



    出现弹框,内容在num1、numb2、number3里随机。


    相关文章

      网友评论

          本文标题:Vue父子组件通信之$emit(基于vue2.5,ES6)

          本文链接:https://www.haomeiwen.com/subject/qjagsftx.html