Computed css class selector, (4n+1) - how? :-)


#1

Hi.

In my component, I want a computed style, that is able to adjust the nth-child programmatically.


li:nth-child(4n+1)


with javascript, how would i change the “4” ?

I where first thinking of a “computed class”, but I don’t know how to do it?


#2

How many options do you have?

You could build, say, 10 switches and set class on ul as you need:

.one li:nth-child(1n+1) { ... }
.two li:nth-child(2n+1) { ... }

#3

That is an option I was thinking of, but I think that the webpack thing that removes unused classes is going to remove them…


#4

Looks like you can just write the HTML of a style element, as long as it’s outside of your Vue app:

Only tested in OSX/Chrome.


#5

Was curious about this, here’s another option: https://jsfiddle.net/jamesbrndwgn/5h0oesvn/1/

Though I quite like Dave’s, 0 manual management of classList and you could conditionally change the styling. Funny we both picked color: red :laughing:


#6

Another option would be using the modulo operator:


#7

Always red! Or hello!

I learnt my lesson using profanities (especially when tired or frustrated) after I checked something fairly unsavoury into an open source codebase one time :grimacing:


#8

lol! :joy:


#9

You can also write a <style> direct to the components template.

<style>
{{ gimmeSomeString() }}
</style>


#10

I’m not familiar with methods inside < style >

I dont think I understand what you mean, can you show a more complete example?

thanks.

By now, I’ve just solved it with the first suggestion as davestewart showed


#11

Another option would be using the modulo operator:

hahahaha so epic solution :smiley: :laughing: :hugs:


#12
const MyComp = {
    template: '<div>
        <style>
            {{ myStyle() }}
        </style>
        <span class=boo>
            boo
        </span>
    </div>',
    methods: {
        myStyle() {
            return '.boo {
                color: ${ this.a ? "blue" : "red"};
        }'
    }
}

#13

Thanks. I’m using webpack, is it possible to mix this with an existing component?

When I try to put the < style > tag inside the < template > tag, webpack just explode :smiley:


#14

Pretty sure the style tag approach is a red herring.

Use the modulo approach and you’re good to go.


#15

Can’t tell why your webpack explodes.
Maybe delegating the complete tag to a computed property works better.

https://jsfiddle.net/x9y2kjmc/1/


#16

If you’re trying that in an SFC it’s likely because <style> must be its own declaration and using it within <template> would be a syntax error as far as vue-loader is concerned. Another option, so you don’t need to rely on including an empty <style> tag in your html, is to create the element on the fly: https://jsfiddle.net/jamesbrndwgn/y5kmeun0/