【问题标题】:Emitting custom events on components在组件上发出自定义事件
【发布时间】:2018-12-24 20:07:42
【问题描述】:

我正在遵循vuejs.org 上的组件基础指南,但我无法按照指导生成结果。我不知道是将methods 属性放在组件上还是放在根Vue 实例上。

当我将方法onIncreaseCount 放入组件时,会引发错误。

但是当我把方法onIncreaseCount放在根Vue实例中时,虽然没有错误,但是当我点击按钮时什么都没有应用。

// JS
Vue.component('button-counter', {
    data: function(){ return {count: 0} }
    template: `<button v-on:click="$emit('increase-count')">You clicked me {{ count }} times.</button>`,
    methods: {
        onIncreaseCount: function(){ this.count++ }
    }
})
new Vue({
    el: "#main"
})
// HTML
<main class="main" id="main">
    <button-counter title="Example component" @increase-count="onIncreaseCount"></button-counter>
</main>

我希望每次单击按钮时{{ count }} 的值都会增加,但不会改变。

【问题讨论】:

标签: vuejs2


【解决方案1】:

你不需要任何发射,你必须调用增加函数

在组件本身中处理

// JS
Vue.component('button-counter', {
    data: function(){ return {count: 0} }
    template: `<button v-on:click="increaseCount">You clicked me {{ count }} times.</button>`,
    methods: {
        increaseCount: function(){ this.count++ }
    }
})
new Vue({
    el: "#main"
})
// HTML
<main class="main" id="main">
    <button-counter title="Example component"></button-counter>
</main>

【讨论】:

  • 是的,我好像误解了发射的概念。它用于在组件和父实例(父组件或本指南中的根实例)之间进行通信。
猜你喜欢
  • 1970-01-01
  • 2021-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-29
  • 1970-01-01
  • 2011-10-16
  • 2013-08-24
相关资源
最近更新 更多