0

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

1
  • 1
    change :style="{top: x}" to :style="`top: ${x}`" you may also need to include !important Commented Aug 2, 2021 at 15:46

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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`" 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.