Hasan Bilal
Hasan Bilal

Reputation: 143

change the style of element dynamically using VUEJS

I have div and I want to change its position dynamically using VueJS app. I have variable x in data function and I want to assign it to top. this is the code I write but it dosn't work in template tag:

<template>
    <div id="squar" v-if="showSquar" :style="{top: x}" @click="countClicks">
        click here
    </div>  
</template>

and in style tag:

#squar{
    width: 100px;
    height: 100px;
    border-radius: 5px;
    background: rgb(0,70,40,0.8);
    color: white;
    text-align: center;
    vertical-align: middle;
    line-height: 100px; 
    position: absolute; 
    
    }

the component that I work in isn't the App component

Upvotes: 0

Views: 3060

Answers (2)

Salvino D&#39;sa
Salvino D&#39;sa

Reputation: 4506

This works for me:

<template>
  <div id="squar" v-if="showSquar" :style="{ top: top + 'px' }">
    click here
  </div>
</template>

<script>
export default {
  data() {
    return {
      showSquar: true,
      top: 200
    };
  }
};
</script>
<style scoped>
#squar {
  width: 100px;
  height: 100px;
  border-radius: 5px;
  background: rgb(0, 70, 40, 0.8);
  color: white;
  text-align: center;
  vertical-align: middle;
  line-height: 100px;
  position: absolute;
}
</style>

Upvotes: 1

Marcello B.
Marcello B.

Reputation: 4440

Right now you are binding a style attribute that won't do anything you need to write it like css

<template>
    <div id="squar" v-if="showSquar" :style="`top:${x}`" @click="countClicks">
        click here
    </div>  
</template>

You may also need to include the !important tag.

:style="`top:${x}!important`" 

Upvotes: 0

Related Questions