I am trying to give a dynamic class to my vue3 app's main div.
When I create the app with the commands down below, it creates a main div tag which has an id app
. I can change the styling with css but since I don't have it in the page I can not change class dynamically.
Code to create the app
const app = createApp(App)
app.use(store)
app.use(router)
app.mount('#app')
<div id="app" :class="myClass"></div>
Unfortunately, you're not going to be able to do that with Vue directly.
Defining :class="myClass"
on root element will not be reactive.
...but you can handle that manually.
you can use this.$el.parentElement
in a method (like mounted
) and that will allow you to manage the class attribute. (there are several methods like addClass
, toggleClass
on the classList API )
If you want that to be reactive, you can use a computed
or watch
to modify that based on some other parameter, but you'd need to provide more context to have more detail on that.
If possible though (depends on the setup/need), you could nest the application in another level of div
, so you can control the class.
You could add property that represent your class then use watch to update the your root element using document.querySelector('#app').classList = [val]
, i made the following example that illustrate a real work example which is the mode change from dark to light and vice-versa, i added property called mode
and i change it using a button click event then i watch it to update the root element class :
const { createApp } = Vue; const App = { data() { return { mode: 'is-light' } }, watch: { mode(val) { document.querySelector('#app').classList = [val] } } } const app = createApp(App) app.mount('#app')
#app { padding: 12px; border-radius: 4px } .is-dark { background: #454545; color: white } .is-light { background: #f9f9f9; color: #222 } button { -webkit-transition: all .2s ease; transition: all .2s ease; padding: 10px; border: 0; border-radius: 6px; cursor: pointer; position: relative; overflow: hidden; color: #fff; -webkit-box-sizing: border-box; box-sizing: border-box; background: transparent; background: #4545ee }
<script src="https://unpkg.com/vue@3.0.0-rc.11/dist/vue.global.prod.js"></script> <div id="app" class="is-dark"> <button @click="mode= 'is-dark'" class="is-dark"> Dark </button> <button @click="mode= 'is-light'" class="is-light"> Light </button> <p> Lorem, ipsum dolor sit amet consectetur adipisicing elit. Corrupti quidem aspernatur provident fugit impedit esse itaque iusto iure voluptatem eaque? </p> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.