首页 > 解决方案 > Vue Js 组件问题 - 处理数据

问题描述

我一直在为一个类开发一个项目,并遇到了一个问题,即组件不能按预期很好地通信。目标是,如果它发送消息的任何组件中有一个错误,则不要转到该位置。这是我目前拥有的一些代码:

    <template>
    <div class="component">
        <h3>Temperature Sensor</h3>

        <input v-model = 'temperature' @keyup.enter = "checkTemp"> </input>
        <p> Action to take : {{ action }} </p>

    </div>
</template>

<script>
import { eventBus } from '../main.js';
export default {

    props :{ 
        action : String
    },
    computed () {
        return {
            //defines a movement value that we will use.
            movement : true,
        };
    },
    mounted(){
        eventBus.$on('move',(movement) =>{
           this.movement = movement;
           if(movement == true){
               this.action = "Go to Location";
           }else{
               this.action = "Dont go There";
           }
        })
    },
    methods : {

        checkTemp(){
            if(this.temperature >=50){
                this.movement = false;
                console.log(this.movement);
                eventBus.$emit('move', this.movement);
            }else {
                this.movement = true;
                console.log(this.movement);
                eventBus.$emit('move', this.movement);
            }
        }
    },

};
</script>

<style scoped>
    div {
        background-color: lightcoral;
    }
</style>

对于第二个组件:

    <template>
    <div class="component">
        <h3> Radiation Drone</h3>
       <input v-model = 'radiation' @keyup.enter = "checkRadiation"></input>
        <p > Action : {{ action }} </p>

    </div>
</template>

<script>
import { eventBus } from '../main.js';

export default {
    props : {

        action : String
    },
    computed () {
        return {
            movement : true,
        }
    },
    mounted(){
        eventBus.$on('move',(movement) =>{
           this.movement = movement;
           if(movement == true){
               this.action = "Go to Location";
           }else{
               this.action = "Dont go There";
           }
        })
    },
    methods : { 
      checkRadiation(){

              if(this.radiation >=34){
                  this.movement = false;
                  console.log(this.movement);
                 eventBus.$emit('dontGo',this.movement);
              }
                else {
                  this.movement = true;
                  console.log(this.movement);
                  this.$root.$emit('goThere',this.movement);
              }

          }
      },
};

</script>

<style scoped>
    div {
        background-color: lightgreen;
    }
</style>

它显示不直接操作道具的错误我只是不知道如何重构我的代码。有什么建议么?

标签: javascriptvue.jscomponents

解决方案


您不能直接从子组件更改 prop 值,而是使用emit调用在父组件中创建的方法


推荐阅读