'How to add style in Vue js 3 on a cdn based app
I'm learning Vue js. I created a Vue JS app with cdn link and I want to know, how to add element style to it.
I can write template as template: <div>Vue js 3</div>
but can style be written like it?
Like -
export default {
data() {
return {
count: 0
}
},
methods: {
increment() {
this.count++
},
},
template : `<button @click="increment">count is: {{ count }}</button>`,
//can style be written like it?
style : {
button {
background : red;
}
}
mounted() {
console.log(`The initial count is ${this.count}.`)
}
}```
Solution 1:[1]
I think this should work for you.
<style>
@import './yourStyles.css';
</style>
Solution 2:[2]
If styles is particular to this component button, then you can use scoped
style.
<style scoped>
button {
background : red;
}
</style>
If you want to apply common style for all the buttons
in an application then you can create a common style file and then import wherever you want to access.
<style>
@import './button.css';
</style>
Demo :
new Vue({
el: '#app',
data: {
count: 0
},
methods: {
increment() {
this.count++
}
}
})
button {
background : red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button @click="increment">count is: {{ count }}</button>
</div>
Solution 3:[3]
In your index file add a main js with script type module
In your component e.g. counter.js add
import sheet from './styles.css' assert { type: 'css' };
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | OndrejHj04 |
Solution 2 | Rohìt JÃndal |
Solution 3 | Anca P?ltineanu |