Vue.如何获取“键"的值?创建元素中的属性 [英] Vue. How to get a value of a "key" attribute in created element

查看:29
本文介绍了Vue.如何获取“键"的值?创建元素中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试创建一个组件并获取其在 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>

这篇关于Vue.如何获取“键"的值?创建元素中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆