【问题标题】:Dynamic variable in attributes seen as undefined属性中的动态变量被视为未定义
【发布时间】:2019-08-19 22:16:02
【问题描述】:

我有 2 个 vue 组件。一个父组件:list of services 存储了许多service 组件。

服务.vue

<template lang="pug">
  a.list-group-item.list-group-item(id='list-' + name + '-list' data-toggle="list" href="#list-" + name role="tab" aria-controls=name) {{ name }}
</template>

<script>
export default {
  props: {
    name: String,
    description: String
  }
}
</script>

List.vue

<template lang="pug">
  section.border-bottom.border-warning
    .container(style="background-color: #EA846F")
      .text-white.text-center.title Serviciile oferite
    .list-group#list-tab(v-if="response.status === 200" role="tablist")
      service(v-for="service in response.data" :name="service.name" :description="service.description")
    .h5.text-muted.text-center(v-else) {{ response.statusText }}
</template>

<script>
import service from './service';

import axios from 'axios';

export default {
  data() {
    return {
      response: {},
    }
  },
  components: {
    service
  },
  methods: {
    async getAll() {
      this.response = await axios.get('http://localhost:3000/infos');
    }
  },
  async mounted() {
    await this.getAll();
  }

为什么name作为道具发送并用于服务模板是undefined?我该如何解决这个问题?

【问题讨论】:

  • 大多数时候它只是undefined,因为它是undefined - 您是否调试过您的回复?
  • @Estradiaz {{ name }} 从标签末尾返回预期值
  • 那么您的问题是什么 - 您没有在其他任何地方使用"name"
  • 问题是:像href href="#list-" + name这样的标签的属性返回我#list-undefined而不是名称值。
  • 让你的 mounted 生命周期挂钩 async 不会完成任何事情。 Vue 不会等待它完成。你还不如mounted() { this.getAll() }

标签: vue.js pug


【解决方案1】:

我根本不认识 Pug,但您似乎需要使用 v-bind 语法,就像您想在属性值中插入道具或数据的任何其他地方一样

a.list-group-item.list-group-item(:id="`list${name}-list`" :href="`#list-${name}`" data-toggle="list"  role="tab" aria-controls=name) {{ name }}

https://vuejs.org/v2/guide/syntax.html#Using-JavaScript-Expressions

我使用过template literals,但您也可以恢复为串联,例如

a(:id="'list' + name + '-list'" ...

我也会,至少初始化response 有一个空的data 数组,这样你就不会尝试在初始显示上迭代undefined,即

return {
  response: {
    data: []
  }
}

【讨论】:

  • 谢谢。那是。属性必须绑定到标签。小观察:我不得不使用完整的语法 v-bind:href 等。只是 :href 给我一个错误
  • @dem.1797 这似乎很奇怪,因为您在 service 元素中使用了 v-bind 速记语法
猜你喜欢
  • 1970-01-01
  • 2022-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-16
  • 2020-04-16
  • 2018-11-12
  • 2020-01-30
相关资源
最近更新 更多