首页  >  问答  >  正文

标题重写为:解决Vue.js 3和Tailwind CSS中RatingBar组件动态宽度渲染问题

<p>我正在使用Vue.js 3和Tailwind CSS。我有一个名为RatingBar的组件,我试图将动态宽度值应用于父元素的class。然而,尽管我在DevTools中可以看到期望的宽度,但它渲染为100%。</p> <p>这是我在RatingBar.vue组件中的代码:</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>渲染的HTML输出在<div>中显示宽度为<code>w-[75%]</code>:</p> <pre class="brush:html;toolbar:false;"><div class="h-full rounded-lg bg-secondary w-[75%]"></div> </前> <p>这是我的package.json文件:</p>
{
  “名称”:“项目名称”,
  “版本”:“0.0.0”,
  “私人”:真实,
  “脚本”:{
    “dev”:“vite”,
    “构建”:“vite 构建”,
    “预览”: “视频预览”
  },
  “依赖关系”:{
    “axios”:“^1.4.0”,
    “firebase”:“^9.22.1”,
    “vue”:“^3.3.2”,
    “vue-router”:“^4.2.0”
  },
  “开发依赖项”:{
    “@vitejs/plugin-vue”:“^4.2.3”,
    “自动前缀”:“^10.4.14”,
    “postcss”:“^8.4.23”,
    “更漂亮”:“^2.8.8”,
    "prettier-plugin-tailwindcss": "^0.3.0",
    "tailwindcss": "^3.3.2",
    “vite”:“^4.3.5”
  }
}

</前>
<p>请问您能帮我解决这个问题吗?</p>
<p>我尝试在RatingBar组件中使用静态值作为宽度,它正确渲染。然而,当我尝试使用动态值作为宽度时,使用表达式:class="w-[${Math .floor(genre. rating * 10)}%]”</code>,渲染结果并不如预期。它总是渲染为宽度为100%,而不是应用计算得到的宽度。

<p>我希望具有bg-secondary类的div元素的宽度与基于genre. rating值计算的百分比相对应。例如,如果genre. rating为7.5,宽度应该是75%。</p> <p>在DevTools中验证了宽度值,但渲染的HTML输出始终将宽度显示为100%,而不管实际计算得到的值如何。</p> <p>我将非常感谢您如何解决此问题,以确保RatingBar组件中的动态框架正确渲染任何意见或建议。</p>
P粉803527801P粉803527801414 天前369

全部回复(1)我来回复

  • P粉262113569

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

    根据文档

    相反,你可以使用style属性来设置width

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

    回复
    0
  • 取消回复