我一直在为一个班级开发一个项目,并遇到了一个问题,即各个组件无法按预期进行良好的沟通。目标是,如果在它发送消息的任何组件中都存在一个错误,则不要转到该位置。这是我目前拥有的一些代码:
<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>
显示不直接操纵道具的错误,我只是不知道如何重构代码。有什么建议吗?
您不能直接从子组件更改prop值,而是使用emit调用在父组件中创建的方法