Home > other >  Where in Vue do I add some code to change the font size dynamically based on a class?
Where in Vue do I add some code to change the font size dynamically based on a class?

Time:11-26

In Vue I have a card set up that can take a max char of 100 and I want to change the font size depending on the number of charters in the card to make the most of the space.

      <v-card
        flex
        @click="editNode(node)"
      >
        <v-card-text
          text-no-wrap
          class="card-text"
          v-text="node.content"
        />
      </v-card>

In JS I want to dynamically change .card-text to change depending on the length of text in the container. Where and how in Vue do I add this?

fontSize = Math.min(Math.max(parseInt(node.content.length/5), 12), 20)

CodePudding user response:

You can bind the font size directly to the styles

<template>
  <v-card flex @click="editNode(node)">
    <v-card-text
      text-no-wrap
      class="card-text"
      v-text="node.content"
      :style="{ fontSize: fontStyleSize(node) }"
    />
  </v-card>
</template>

<script>
export default {
  methods: {
    editNode(node) {
        // ...
    },
    fontStyleSize(node) {
      return {
        fontSize: Math.min(Math.max(parseInt(node.content.length / 5), 12), 20),
      };
    },
  },
};
</script>

CodePudding user response:

<template>
    <v-card flex @click="editNode(node)">
        <v-card-text text-no-wrap class="card-text" v-model="nodeContent"/>
    </v-card>
</template>

<script>
export default {
    data() {
        return {
            nodeContent : '',
            textSize : '0px'
        }
    }, 
    watch:{
        nodeContent(val, oldVal){
            this.textSize = Math.min(Math.max(parseInt(val.length/5), 12), 20).toString()   'px';
            console.log(this.textSize);
        }
    }
}
</script>

<style>
    .card-text{
        font-size: v-bind('textSize');
    }
</style>
  • Related