Home  >  Q&A  >  body text

The title is rewritten as: Solving the dynamic width rendering problem of RatingBar component in Vue.js 3 and Tailwind CSS

<p>I'm using Vue.js 3 and Tailwind CSS. I have a component called RatingBar and I'm trying to apply a dynamic width value to the parent element's class. However, although I can see the expected width in DevTools, it renders at 100%. </p> <p>This is my code in the RatingBar.vue component: </p> <pre class="brush:js;toolbar:false;"><template> <div class="my-2 grid grid-cols-3 items-center"> <span class="text-left text-sm">{{ genre.name }}</span> <div class="h-2 flex-1 rounded-lg bg-gray-800"> <div class="h-full rounded-lg bg-secondary" :class="`w-[${Math.floor(genre.rating * 10)}%]`" ></div> </div> <div class="ml-2 flex flex-row items-center gap-1 text-sm text-gray-600"> <i class="fa-regular fa-star"></i> <span class="flex flex-row gap-1"> <span> {{ genre.rating }} </span> <span> ({{ genre.count }}) </span> </span> </div> </div> </template> <script setup> const props = defineProps({ genre: { type: Object, required: true, }, }) </script> </pre> <p>Rendered HTML output displays in <div> with width <code>w-[75%]</code>: </p> <pre class="brush:html;toolbar:false;"><div class="h-full rounded-lg bg-secondary w-[75%]"></div> </pre> <p>这是我的package.json文件:</p> <pre class="brush:json;toolbar:false;">{ "name": "project_name", "version": "0.0.0", "private": true, "scripts": { "dev": "vite", "build": "vite build", "preview": "vite preview" }, "dependencies": { "axios": "^1.4.0", "firebase": "^9.22.1", "vue": "^3.3.2", "vue-router": "^4.2.0" }, "devDependencies": { "@vitejs/plugin-vue": "^4.2.3", "autoprefixer": "^10.4.14", "postcss": "^8.4.23", "prettier": "^2.8.8", "prettier-plugin-tailwindcss": "^0.3.0", "tailwindcss": "^3.3.2", "vite": "^4.3.5" } } </pre> <p>请问您能帮我解决这个问题吗?</p> <p>我尝试在RatingBar组件中使用静态值作为宽度,它正确渲染。然而,当我尝试使用动态值作为宽度时,使用表达式<code>:class="w-[${Math.floor(genre.rating * 10)}%]"</code>,渲染结果并不如预期。它总是渲染为宽度为100%,而不是应用计算得到的宽度。</p> <p>我期望具有bg-secondary类的div元素的宽度与基于genre.rating值计算的百分比相对应。例如,如果genre.rating为7.5,宽度应该是75%。</p> <p>尽管在DevTools中验证了宽度值,但渲染的HTML输出始终将宽度显示为100%,而不管实际计算得到的值如何。</p> <p>我将非常感谢您对如何解决此问题并使RatingBar组件中的动态宽度正确渲染的任何见解或建议。</p>
P粉803527801P粉803527801414 days ago374

reply all(1)I'll reply

  • P粉262113569

    P粉2621135692023-09-02 09:40:10

    According to documentation:

    Instead, you can use the style attribute to set the width:

    <div
      class="h-full rounded-lg bg-secondary"
      :style="{ width: `${Math.floor(genre.rating * 10)}%` }"
    ></div>
    

    reply
    0
  • Cancelreply