0%

vue实例方法事件

vm.$on(event, callback)

  • 参数:
    • {string | Array} event
    • {Function} callback
  • 用法:
    监听当前实例上的自定义事件, 事件可以由 vm.$emit 触发. 回调函数会接受所有传入事件触发函数的额外参数
  • 示例:
    1
    2
    3
    4
    5
    vm.$on('test', function(msg) {
    console.log(msg)
    })
    vm.$emit('test', 'Ginger')
    // => Ginger

vm.$once(event, target)

  • 参数:
    • {string} event
    • {Function} callback
  • 用法:
    监听一个自定义事件, 但是只触发一次, 一旦触发之后, 监听器就会被移除

vm.$off(event, callback)

  • 参数:
    • {string | Array} event
    • {Function} [callback]
  • 用法
    移除自定义事件监听器
    • 如果没有提供参数, 则移除所有事件监听器
    • 如果只提供了事件, 则移除该事件的所有监听器
    • 如果同时提供了事件与回调, 则只移除这个回调的监听器

vm.$emit(eventName, […args])

  • 参数:

    • {string} eventName
    • […args]
      触发当前实例上的事件
  • 示例:
    只配合一个事件名使用 $emit

    1
    2
    3
    4
    5
    6
    7
    Vue.component('welcome-button', {
    template: `
    <button v-on:click="$emit('welcome')">
    Click me to be welcomed
    </button>
    `
    })
    1
    2
    3
    <div id="emit-example-simple">
    <welcome-button v-on:welcome="sayHi"></welcome-button>
    </div>
    1
    2
    3
    4
    5
    6
    7
    8
    new Vue({
    el: '#emit-example-simple',
    methods: {
    sayHi: function() {
    alert('Hi!')
    }
    }
    })

    配合额外的参数使用 $emit

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    Vue.component('magic-eight-ball', {
    data: function() {
    return {
    possibleAdvice: ['Yes', 'No', 'Maybe']
    }
    },
    methods: {
    giveAdvice: function() {
    var randomAdviceIndex = Math.floor(
    Math.random() * this.possibleAdvice.length
    )
    this.$emit('give-advice', this.possibleAdvice[randomAdviceIndex])
    }
    },
    template: `
    <button v-on:click="giveAdvice">
    Click me for advice
    </button>
    `
    })
    1
    2
    3
    <div id="emit-example-argument">
    <magic-eight-ball v-on:give-advice="showAdvice"></magic-eight-ball>
    </div>
    1
    2
    3
    4
    5
    6
    7
    8
    new Vue({
    el: '#emit-example-argument',
    methods: {
    showAdvice: function(advice) {
    alert(advice)
    }
    }
    })
请作者喝杯咖啡