我在Main2.vue中发出了一个称为emit-event-main2-counter的事件

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

应用程序

<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>


Main2.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>


底线

<template>
  <div  class="Bottom" v-on:emit-event-main2-counter="cntr = $event">
      bottom text and cntr ({{cntr}})
  </div>
</template>

<script>

export default {
    data: () => {
        return {
            cntr: 0
        }
    },
}
</script>

<style scoped>

</style>

最佳答案

您可以从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"]


底线

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

  <script>

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

07-24 18:17