javascript - 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>
它显示不直接操作道具的错误我只是不知道如何重构我的代码。有什么建议么?
解决方案
您不能直接从子组件更改 prop 值,而是使用emit调用在父组件中创建的方法
推荐阅读
- docker - 如何使用 redis-rs 从 Docker 容器内部连接到 Redis?
- c - 为什么我得到这个单一的输出错误?
- java - 检查多行字符串是否仅包含 Java 中用 1 个逗号分隔的 2 个数字
- php - (PHP + MongoDB + Laravel jenssegers)无法向数据库发送“count”命令:套接字错误或超时
- vba - Outlook:根据签名发送计数
- java - 如何正确创建实体/对象?
- java - 实现观察者模式 Android
- swift - 如何使 PDFView 从文档顶部开始?
- django - 尝试使用 VS Code 在虚拟环境中安装 Django 时出错,但出现错误
- html - 如何在 nuxtjs 中显示来自存储(Laravel)的图像