我一直在为一个类开发一个项目,遇到了一个问题,组件不能像预期的那样很好地通信。我们的目标是,如果在它发送消息的任何组件中都有一个false,那么就不要去这个位置。这是我目前拥有的一些代码:
<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>它显示了一个错误,没有直接操作道具,我只是不知道如何重构我的代码。有什么建议吗?
发布于 2019-11-28 04:27:28
您不能直接从子组件更改prop值,而是使用emit调用在父组件中创建的方法
https://stackoverflow.com/questions/59077749
复制相似问题