【问题标题】:Vuejs template list array values which its keys starts with special stringVuejs 模板列表数组值,其键以特殊字符串开头
【发布时间】:2022-07-16 06:38:47
【问题描述】:

我有一个 vuejs 模板,它显示嵌套数组的值。 示例数组是:

myArray : [
{
  name: "abc",
  
},
{
  name123: "bcf"
},
{
  name12456: "fdf"
}
]
<template> 
<div>
{{ node.name }}
</div>
</template>

当我调用这个数组的对象时,我可以用 {{ node.name }} 显示“abc”值,但我想显示以“name”字符串开头的键。因此,通过这种方式,我可以列出所有值。

注意:我只想显示以“名称”开头的键。不同的数组可能有不同的key。

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    您可以尝试使用computed 属性和Object.keys

    new Vue({
      el: '#demo',
      data() {
        return {
          myArray: [
            {name: "abc"}, 
            {nn00: 'rrr'},
            {name123: "bcf", ar: [{name9: 'nested1'}]}, 
            {name12456: "fdf"}, 
            {no78: "eee", ar: [{name8: 'nested2'}]}],
          res: []
        }
      },
      methods: {
        getValues(arr) {
          arr.forEach(a => {
            let val = Object.keys(a).filter(k => {
              if (typeof a[k] === 'object') this.getValues(a[k])
              return k.startsWith('name')
            })
            this.res.push(a[val])
          })
        }
      },
      mounted() {
        this.getValues(this.myArray)
      }
    })
    
    Vue.config.productionTip = false
    Vue.config.devtools = false
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="demo">
      <div v-for="(node, i) in res" :key="i">
      {{ node }}
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多