Reputation: 117
How can I set data-* attributes of a div dynamically via an array or object in Vue.js?
I found out that it is possible to set attributes dynamically via the data attributes or via calculated properties. But the problem is that I don't know how to name the calculated properties so that they end up with the attribute name "data-customer-firstname", for example.
Link to the vue.js doc
I hope someone have an idea to solve the problem.
EDIT (here is an example):
<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>
Upvotes: 1
Views: 2381
Reputation: 1
Try to return the attribute name from the computed properties not the value :
<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>
Upvotes: 0
Reputation: 151
Try simply like below:
<div :data-country="dataCountry"></div>
and so on, with all the necessary attributes!
Upvotes: 2