Vue.如何获取“键"的值?创建元素中的属性

2022-01-25 00:00:00 vue.js vue-component vuejs2

我尝试创建一个组件并获取其在 axios 中使用的密钥.元素已创建,但我无法获得密钥.未定义

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>

我尝试了一些变体,但没有结果 - @key 为空.

I try some variants, but no result - @key was empty.

推荐答案

这个答案回答了如何将密钥传递给子组件的问题.如果您只想从子组件内部获取当前密钥,请使用投票最高的答案.<小时>key 是 Vue 中的 特殊属性.您必须将您的财产称为其他名称.

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.

这里是使用 pkey 的替代方法.

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>

相关文章