在Vue.js中设置div元素的data-* 属性

brc7rcf0  于 2022-11-17  发布在  Vue.js
关注(0)|答案(2)|浏览(329)

如何通过Vue.js中的数组或对象动态设置div的data-* 属性?
我发现可以通过数据属性或计算属性动态设置属性,但问题是我不知道如何命名计算属性,例如,使它们以属性名“data-customer-firstname”结束。
链接到vue.js文档
我希望有人有办法解决这个问题。
EDIT(以下是一个示例):

<template>
  <div class="content">

    <div
        :[dataCountry]
        :[dataApplicantFirstname]
        :[dataApplicantLastName]
    ></div>

    <!-- the result I needed -->

    <div
      data-country="ukraine"
      data-applicant-firstname="Doe"
      data-applicant-lastname="Joe"
    >
    </div>

    <!--
    but if one of them is "null" it should be ignored
    for example if the country and the firstname are "null" so it
    should be ignored and it should likes so:
    -->
    <div
        data-applicant-lastname="Joe"
    >
    </div>

  </div>
</template>

<script>
export default {
  name: "ExampleComponent",
  data() {
    return {
      country:"ukraine",
      firstname: "Doe",
      lastname: "Joe"
    }
  },
  computed: {
    dataCountry: function () {
      return (this.country !== "") ? this.country : null;
    },
    dataCustomerFirstname:function (){
      return (this.firstname !== "")?this.firstname : null;
    },
    dataCustomerLastName:function (){
      return (this.lastname !== "")?this.lastname : null;
    },

  },
}
</script>
kdfy810k

kdfy810k1#

试简单地像下面这样:

<div :data-country="dataCountry"></div>

等等,具有所有必要的属性!

l7mqbcuq

l7mqbcuq2#

尝试从计算的属性(Property)传回属性(Attribute)名称,而不是值:

<div
      :[dataCountry]="country"
      :[dataCustomerFirstname]="firstname"
      :[dataCustomerLastname]="lastname"
    >

<script>
export default {
  name: "ExampleComponent",
  data() {
    return {
      country:"ukraine",
      firstname: "Doe",
      lastname: "Joe"
    }
  },
  computed: {
    dataCountry: function () {
      return (this.country !== "") ? 'data-applicant-country': '';
    },
    dataCustomerFirstname:function (){
      return (this.firstname !== "")? 'data-applicant-firstname' :'';
    },
    dataCustomerLastName:function (){
      return (this.lastname !== "")?'data-applicant-lastname' :''
    },

  },
}
</script>

相关问题