I try to create a components and get its key for using in axios. Elements created, but I can't get a key. It's undefined
<div class="container" id="root"> <paddock is="paddock-item" v-for="paddock in paddocks" :key="paddock.key" class="paddock"> </paddock> </div> <script> var pItem = { props: ['key'], template: '<div :test="key"></div>', created: function() { console.log(key); } }; new Vue({ el: '#root', components: { 'paddock-item': pItem }, data: { paddocks: [ {key: 1}, {key: 2}, {key: 3}, {key: 4} ] } }) </script>
I try some variants, but no result - @key was empty.
we will write button click event and get custom attribute value in vue. js. In this example we will take on button with custom attribute like "data-id" and on click event of button we will get that value of custom data attribute value in console. we will get data attribute value using event.
key # The key special attribute is primarily used as a hint for Vue's virtual DOM algorithm to identify vnodes when diffing the new list of nodes against the old list. Without keys, Vue uses an algorithm that minimizes element movement and tries to patch/reuse elements of the same type in-place as much as possible.
The Key attribute is used to denote the property that uniquely identifies an entity (the EntityKey ), and which is mapped to the Primary Key field in a database: public class Order. { [Key]
The key attribute gives Vue hints You, as the developer, need to give Vue some hints every now and then. The key attribute tells Vue how your data relates to the HTML elements it's rendering to the screen.
you don't need to use an extra attribute. You can get the key by
this.$vnode.key
This answer answers the question of how you would pass the key to a child component. If you just want to get the current key from inside the child component, use the highest voted answer.
key
is a special attribute in Vue. You will have to call your property something else. Here is an alternative using pkey
instead.
console.clear() var pItem = { props: ['pkey'], template: '<div :test="pkey"></div>', created: function() { console.log(this.pkey); } }; new Vue({ el: '#root', components: { 'paddock-item': pItem }, data: { paddocks: [{ key: 1 }, { key: 2 }, { key: 3 }, { key: 4 } ] } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script> <div class="container" id="root"> <paddock-item v-for="paddock in paddocks" :pkey="paddock.key" :key="paddock.key" class="paddock"> </paddock-item> </div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With