简体   繁体   中英

Tried to apply css to a component conditionally using prop but its not working

 .storyMobile{ color:green; } .storyWeb{ color:red; } 
 <div class="storyMobile"> hii </div> <div class="storyWeb"> hii </div> //main view <div> <story :story="stories[0]"/> </div> //here it prints stories in red colour but I want it to be displayed in green colour - how can I do this? 

This is my component where I have 2 divs with 2 different classes one will be active for mobile and one will be active for web.

<div class="storyMobile">
//code
</div>

 <div class="storyWeb">
//code
</div>

//this is my main view where I am importing this component

<div class="body-frame">
    <Header></Header>
    <section class="content-section-bar" v-if="stories && stories.length">

      <div>
        <story   :story="stories[0]"/>
      </div>
    </section>
</div>

By default the story component is in web so "storyweb" class is getting applied to it but I want the "storyweb" class to get applied on it.

How should I do it in vue.js I tried using the props but didn't get the desired output.

Is it what you want?

your component:

<div :class="className"></div>

script:

export default {
  props: {
    className: {
      default: 'storyWeb'
    }
  }
}

usage:

<story :story="stories[0]"/>
<story :story="stories[0]" class-name="storyMobile"/>

 Vue.component('story',{ template: `<div :class="className">test</div>`, props: { className: { type: String, default: 'storyWeb' }, story: { type: Object, required: true } } }) var app = new Vue({ el: '#app', data () { return { stories: [ {content: 'sotry1 content'}, {content: 'story2 content'} ] } } }) 
 .storyMobile{ color:green; } .storyWeb{ color:red; } 
 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div id="app"> <story :story="stories[0]" class-name="storyMobile"></story> <story :story="stories[1]"></story> </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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM