vue-dom元素绑定动态样式

众所周知,vue是操作dom元素的。那么如果有元素要动态绑定样式,这种需求,还是要通过改变数据来改变视图的样式。
例子:
在这个table自定义组件中,caption元素的宽度保持了table宽度一致,可以借助计算属性。
上代码:

<template>
  <div>
    <caption :style="{ width: capWidth }">
      {{
        tableTit
      }}
    </caption>
    <table
      :border="border"
      :cellpadding="cellpadding"
      :cellspacing="cellspacing"
      :width="width"
      id="customTable"
    >
      <tr v-for="item in dataTable" :key="item.val1">
        <th>{{ item.val1 }}</th>
        <th>{{ item.val2 }}</th>
      </tr>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // capWidth:""
    };
  },
  props: {
    border: {
      type: String,
      default: "2"
    },
    cellpadding: {
      type: String,
      default: "15"
    },
    cellspacing: {
      type: String,
      default: "20"
    },
    width: {
      type: String,
      default: "800"
    },
    tableTit: {
      type: String,
      default: "表格标题"
    },
   
    }
  },
  computed: {
    //   动态的设置dom元素的宽度
    capWidth() {
      let ctx = this;
      let capWidth = "";
      if (ctx.width) {
        capWidth = ctx.width;
      }
      return capWidth + "px";
    }
  },
  watch: {}
};
</script>

<style>
caption {
  width: 500px;
}
</style>

posted @ 2022-11-22 17:41  皮皮买  阅读(271)  评论(0编辑  收藏  举报