代码之家  ›  专栏  ›  技术社区  ›  Rakesh Adhikesavan

如何基于另一个元素更新元素的宽度?

  •  0
  • Rakesh Adhikesavan  · 技术社区  · 6 年前

    我正在建立一个琐事应用程序,我有一个 <h1> b-form-group 是一个 Bootstrap-Vue component <

    example image of the desired output watchers buttonWidth 无论什么时候 question 变化。但是,使用此代码,按钮组的宽度似乎与上一个问题的宽度匹配,而不是与当前问题的宽度匹配。我也试过其他的属性,比如 updated , mounted , created

    <template>
      <div>
        <div id="question">
           <h1 ref="quest">{{ question }}</h1>
        </div>
    
        <b-form-group>
          <b-form-radio-group :style=getWidth
            ref="opts"
            :options="options"
            buttons
            stacked
            button-variant="outline-primary"
            size="lg"
            name="radio-btn-stacked"
          ></b-form-radio-group>
        </b-form-group>
      </div>
    </template>
    

    export default {
      props: ['question', 'options'],
      data() {
        return {
          buttonWidth: '0 px',
        };
      },
      methods: {
      },
      watch: {
        question() {
          // console.log('Updating button width to ', this.$refs.quest.clientWidth);
          this.buttonWidth = `width: ${this.$refs.quest.clientWidth}px;`;
        },
        // immediate: true,
      },
      computed: {
        getWidth() {
          return this.buttonWidth;
        },
      },
    };
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   skirtle    6 年前

    让它和一个 watch 你需要一个 $nextTick

    watch: {
      question() {
        this.$nextTick(() => {
          this.buttonWidth = `width: ${this.$refs.quest.clientWidth}px;`;
        })
      }
    }
    

    它也应该有可能让这个工作与 mounted updated . 你不应该需要 $nextTick公司 如果你那样做的话。你在问题中提到你已经试过了,但是如果没有看到你试过的代码,很难知道为什么那对你不起作用。

    getWidth . 为什么不用呢 buttonWidth 直接?

        2
  •  0
  •   Rakesh Adhikesavan    6 年前

    我的错误是使用 clientWidth h1

    <template>
      <div class="text-center center">
        <div id="question">
           <h1 ref="quest"><span ref="span">{{ question }}</span></h1>
        </div>
    
        <b-form-group>
          <b-form-radio-group :style=buttonWidth
            ref="opts"
            :options="options"
            buttons
            stacked
            button-variant="outline-primary"
            size="lg"
            name="radio-btn-stacked"
          ></b-form-radio-group>
        </b-form-group>
      </div>
    </template>
    
    <script>
    export default {
      props: ['question', 'options'],
      data() {
        return {
          buttonWidth: 'width: 500px',
          value: 0,
        };
      },
      watch: {
        question() {
          console.log('Watcher is updating buttonWidth to ', this.$refs.quest.clientWidth);
          this.$nextTick(() => {
            console.log(this.$refs.span.offsetWidth);
            this.buttonWidth = `width: ${this.$refs.span.offsetWidth}px;`;
          });
        },
      },
    };
    </script>
    
    推荐文章