Home > Blockchain >  Computed function return classes using template string
Computed function return classes using template string

Time:10-07

So I have a computed function where I want to use a dynamic variable. I am having trouble because even though I am using my template string, the variable colorClassName is not recognized. This is only working like this:

It is like this now: (works)

 <div :>
    ...
 </div>

desired outcome:

 <div :>
    ...
 </div>

and in my setup:

const className= computed(() => {
  return {
    '`my-class-${colorClassName}`': props.myProp,
  }
})

I return className and colorClassName

CodePudding user response:

If I understood you correctly , try like in snippet below:

const { ref, computed } = Vue
const app = Vue.createApp({
  setup() {
    const myClass = ref(true)
    const change = () => {
      myClass.value = !myClass.value
    }
    return { myClass, change }
  },
})
app.component('myComp', {
  template: `
    <div :>
      <button @click="color">color</button>
      {{ colorClassName }}
    </div>`,
  props: ['myProp'],
  setup(props) {
    const colorClassName = ref('red')
    const className= computed(() => {
      return {
        [`my-class-${colorClassName.value}`]: props.myProp,
      }
    })
    const color = () => {
      colorClassName.value = colorClassName.value === 'red' ? 'green' : 'red'
    }
    return { className, colorClassName, color }
  },
})
app.mount('#demo')
.my-class-red {
  color: red;
}
.my-class-green {
  color: green;
}
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <button @click="change">toggle</button>
  <my-comp :my-prop="myClass"></my-comp>
</div>

  • Related