首页 > 解决方案 > VueJS/Nuxt 样式绑定仅适用于硬重载

问题描述

我有一个 Vue/Nuxt 项目,但我遇到了一个奇怪的问题。

我有一个组件可以呈现具有各种 CSS 样式的按钮,并且一切正常。我还有一些需要通过道具控制的样式,所以我将它们绑定到样式标签。这一切都适用于页面的初始加载,但是,如果我使用 Nuxt 链接导航到页面,或者我对组件进行了更改并且 HMR 重新加载它,那么内联样式就会消失。

我试图通过包含来自道具的内联样式和我刚刚硬编码的内联样式来缩小范围。和以前一样,不会渲染来自 prop 的样式,但会渲染硬编码的样式。

我有一个很好的谷歌,但找不到任何表明我做错了什么的东西。

编辑:所以我缩小了一点。这不是道具,而是线性渐变。即使是硬编码的线性渐变也不会渲染。

这是组件片段。

<template>
  <span class="button-link" :class="{ 'button-link--primary': primary }">
    <span
      class="button-link__gradient-wrapper-one"
      :style="{
        backgroundImage: `linear-gradient(to left, ${colorStart}, ${colorEnd});`,
        color: 'red'
      }"
    />
    <span
      class="button-link__gradient-wrapper-two"
      :style="{
        backgroundImage: `linear-gradient(to left, ${colorEnd}, ${colorStart});`,
        color: 'red'
      }"
    />
    <button v-if="!href && !to" class="button-link__button">
      <slot />
    </button>
    <a v-if="href" class="button-link__button" :href="href"><slot /></a>
    <nuxt-link v-if="to" :to="to" class="button-link__button">
      <slot />
    </nuxt-link>
  </span>
</template>

<script>
export default {
  props: {
    primary: {
      type: Boolean,
      default: false
    },
    colorStart: {
      type: String,
      default: null
    },
    colorEnd: {
      type: String,
      default: null
    },
    href: {
      type: String,
      default: null
    },
    to: {
      type: String,
      default: null
    }
  }
};
</script>

谢谢

标签: vuejs2nuxt.js

解决方案


尝试使用计算属性。例如:

<template>
  ...
    <span
      class="button-link__gradient-wrapper-one"
      :style="gradientStart"
    />
    <span
      class="button-link__gradient-wrapper-two"
      :style="gradientEnd"
    />
  ...
</template>
computed: {
  gradientStart() {
    return {
      backgroundImage: `linear-gradient(to left, ${this.colorStart}, ${this.colorEnd})`,
      color: "red"
    };
  },
  gradientEnd() {
    return {
      backgroundImage: `linear-gradient(to left, ${this.colorEnd}, ${this.colorStart})`,
      color: "red"
    }
  }
}

推荐阅读