Vue Js Component问题-处理数据

时间:2019-11-27 20:06:31

标签: javascript vue.js components

我一直在为一个班级开发一个项目,并遇到一个问题,即各个组件无法按预期进行良好的通信。目标是,如果在它发送消息的任何组件中都存在一个错误,则不要转到该位置。 这是我目前拥有的一些代码:

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

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

1 个答案:

答案 0 :(得分:0)

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