为什么组件不响应自定义事件?

时间:2018-11-17 12:12:43

标签: javascript vue.js vuejs2 vue-component

我正在 Main2.vue

中发出一个名为 emit-event-main2-counter 的事件

为什么Bottom.vue中的数据cntr无法更新?

App.vue

._take()

Main2.vue

<template>
  <div class="app">
    <Main2 />
    <Bottom/>
  </div>
</template>

<script>
import Main2 from "./components/Main2";
import Bottom from "./components/Bottom";

export default {
  components: {
    Main2,
    Bottom
  },

}
</script>

<style scoped>
  h1 {
    color: red;
  }
</style>

Bottom.vue

<template>
    <div>
        main2 template <span class="text1">{{message}}</span>
        <button type="button" v-on:click="btnClickButton">my click</button>
        <div>{{counter}}</div>

    </div>
</template>

<script>
    import appInput from "./appInput.vue";
    export default {
        data: () => {
            return {
                message: "theText",
                counter: 0,
            }
        },
        components: {
           appInput,
       },
        methods: {
            btnClickButton(e) {
                this.$root.$emit('emit-event-main2-counter', this.counter)
                console.log('button');
                this.counter +=1;
            }
        }

    }
</script>

<style scoped>
.text1 {
    color:red;
}
.text2 {
    color:blue;
}
</style>

2 个答案:

答案 0 :(得分:3)

您可以将Main2作为参数this.counter向父级发送事件,并在父级中接收事件并将其通过props传递到Bottom

Main2中:

this.$emit("emit-event-main2-counter",this.counter);

parent组件中:

  <template>
   <Main2 v-on:emit-event-main2-counter="sendToBottom"/>
   <Bottom :cntr="pcounter"/>
  ....
  </template>


  data:{
   pcounter:0
    },
  methods:{
       sendToBottom(c){
        this.pcounter=c
          }
      }

Bottom应该具有名为cntr

的属性
  props:["cntr"]

Bottom.vue

     <template>
      <div  class="Bottom" >
          bottom text and cntr ({{cntr}})
      </div>
    </template>

  <script>

    export default {
           props:["cntr"],
         data: () => {
             return {
                }
            },
       }
     </script>

答案 1 :(得分:2)

如果要使用根事件,则需要使用this.$root.$emit()发出事件,并在根上监听事件,如下所示:this.$root.$on()

您应该直接在脚本部分中使用它。听根事件,例如created()挂钩中,然后在beforeDestroy()挂钩中使用$off禁用它。


但是,我不鼓励您使用$root事件。通常最好在answer中提出的@BoussadjraBrahim之类的组件之间进行通信。

如果您有一个更复杂的应用程序,则有必要查看Vuex并将完整状态存储在Vuex存储中。这样,您可以监视组件中的全局应用程序状态,并在其更改时做出反应。在这种情况下,您将使用Vuex存储而不是根EventBus。