首页 > 解决方案 > 如何发出改变 CSS 样式的事件

问题描述

我想eventBusApp.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>

标签: javascriptvue.js

解决方案


首先将您的模态组件直接放入App.vue. 还定义数据属性,例如showModalmodalType将包含有关模式的数据。在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' });

推荐阅读