javascript - 如何发出改变 CSS 样式的事件
问题描述
我想eventBus
在App.vue
组件中创建一个可以从我的应用程序中的任何位置调用的组件,并基于作为对象的有效负载更改模式的 CSS。如果我通过{ type: 'success' }
它应该将边框更改为绿色,如果我通过{ type: 'danger' }
它应该将其变为红色。示例调用:
EventBus.$emit('call-modal', { type:'success' });
我将我的模态样式作为对象保留在父级中,但不知道如何根据有效负载更改 CSS,那么如何使用eventBus
?
Gere 是我的示例组件:
<template>
<div>
<button class="pleeease-click-me" @click="callModal()">Click me</button>
<div class="modal" v-show="showModal">
<h2>Messsage</h2>
</div>
</div>
</template>
<script>
import { EventBus } from '../App.vue';
export default {
name: 'bankAccount',
props: ['modalType'],
data() {
return {
showModal: false
}
},
methods: {
callModal() {
this.showModal = !this.showModal
// Send the event on a channel (i-got-clicked) with a payload (the click count.)
EventBus.$emit('call-modal', {type:'success'});
}
}
}
</script>
<style scoped>
.modal {
height: 100px;
width: 300px;
border: solid gray 2px;
}
</style>
还有我的 App.vue 组件:
<template>
<div id="app">
<bankAccount/>
</div>
</template>
<script>
import bankAccount from './components/bankAccount.vue'
import Vue from 'vue';
export const EventBus = new Vue();
EventBus.$on('call-modal', (type) => {
})
export default {
data() {
modalTypes = [
{ type: 'success' },
{ type: 'danger' },
]
},
name: 'app',
components: {
bankAccount
},
}
</script>
<style>
</style>
解决方案
首先将您的模态组件直接放入App.vue
. 还定义数据属性,例如showModal
和modalType
将包含有关模式的数据。在created
钩子中只观察call-modal
事件,并更改本地数据属性。不要忘记根据modalType
值绑定适当的类。而已。
<template>
<div id="app">
<bankAccount />
<div :class="['modal', `modal--type--${modalType}`]" v-show="showModal">
<h2>Messsage</h2>
</div>
</div>
</template>
<script>
import bankAccount from './components/bankAccount.vue'
import Vue from 'vue'
export const EventBus = new Vue()
export default {
name: 'app',
components: {
bankAccount,
},
data() {
return {
showModal: false,
modalType: 'default',
}
},
created() {
EventBus.$on('call-modal', obj => {
this.showModal = true
this.modalType = obj.type
})
},
}
</script>
<style>
.modal {
height: 100px;
width: 300px;
border: solid gray 2px;
}
.modal--type--success {
border-color: green;
}
</style>
要打开模式,只需'call-modal'
通过EventBus
.
EventBus.$emit('call-modal', { type: 'success' });
推荐阅读
- python - Django AttributeError:类型对象“房间”没有属性“对象”
- c# - C#使用循环检查Windows窗体中的按钮点击
- azure-devops - Azure DevOps VsTest 任务版本 2.167.1 失败
- c# - 如何实现 Maxwell 的分布?
- excel - 在 Excel 中将单元格的内容保存到不带引号的 csv
- javascript - 无法在表单提交时删除“PreventDefault”事件侦听器 (JavaScript)
- kubernetes - Airflow KubernetesPodOperator AirflowException('Pod Launching failed: {error}'.format(error=ex))
- visual-studio-code - 指定 tasks.json shell 命令的路径
- vue.js - Visual Studio 代码:找不到模块 - app.vue
- razor - 是否可以通过 2sxc c# razor 模板加载 DNN 皮肤对象?