【问题标题】:Changing v-data-table status when getting RestAPI using axios method使用 axios 方法获取 Rest API 时更改 v-data-table 状态
【发布时间】:2020-12-10 10:21:06
【问题描述】:

我制作了应用程序,我想根据客户 ID 更改 v-data-table 的状态。 所以我在下面做了我的样本。但没有显示任何状态信息。 我使用 axios 来获取 RestAPI。当来自 RestAPI 的 id 为 1 或 3 时,在数据表中显示“超级客户”。 有人给我建议吗?

    <template>
  <v-app>
    <v-data-table 
     dense 
     :headers="headers" 
     :items="items" 
     class="elevation-1">
      <template v-slot:items="{items}">
        <tbody>
          <tr v-for="item in items" :key="item.id">
            <td>{{item.id}}</td>
            <td>{{item.email}}</td>
            <td>{{item.name}}</td>
            <td>{{item.status}}</td>
          </tr>
        </tbody>
      </template>
      </v-data-table>
  </v-app>
</template>

<script lang="ts">
import { Component, Vue } from 'nuxt-property-decorator'
import axios from 'axios'

@Component
export default class AxiosPractice extends Vue {
  items: any=[]
  status:string=''

  headers = [
    { text: 'id', value: 'id' },
    { text: 'name', value: 'name' },
    { text: 'email', value: 'email' },
    { text: 'status', value: 'status' }
  ];
  async mounted() {
    const response = await axios.get(
      'https://jsonplaceholder.typicode.com/posts/1/comments'
    );
    this.items = response.data.map((item:any) => {
      const newStatus =
        item.id === '1' || item.id === '3' ? 'supercustomer' : '';
      return {
        id: item.id,
        email: item.email,
        name: item.name,
        status: newStatus
      };
 });
    if(this.items.id = '1' || '3'){
      return this.status = 'supercustomer'
    }
  }
}
</script>

【问题讨论】:

    标签: typescript vue.js vuetify.js


    【解决方案1】:

    如何显示状态:

    1. Status 必须是 item 的一部分,否则所有项目的状态都相同。所以将&lt;td&gt;{{status}}&lt;/td&gt; 更改为&lt;td&gt;{{item.status}}&lt;/td&gt;。 并将{ text: 'status', value: '' } 更改为{ text: "status", value: "status" }
    2. this.items.id 无效,因为 this.items 是一个数组。
    3. 此外,当您检查一个值是否等于字符串时,您应该使用===,这意味着相等的值和相等的类型。在此处查看有关比较的更多信息:https://www.w3schools.com/js/js_comparisons.asp

    我要做的是在映射项目时添加status

    this.items = response.data.map(item => {
          const newStatus =
            item.id === '1' || item.id === '3' ? 'supercustomer' : '';
          return {
            id: item.id,
            email: item.email,
            name: item.name,
            status: newStatus
          };
     });
    

    【讨论】:

    • 感谢您的建议。对此,我真的非常感激。我试图编辑我的代码,但它没有用。我以为我误解了你的建议。我编辑我的问题代码。你能给我建议吗?
    • codesandbox: codesandbox.io/s/cool-darkness-fwhv8?file=/src/components/… 注意我没用过typescript,但是核心应该是一样的。
    猜你喜欢
    • 2023-03-09
    • 2019-07-23
    • 2022-08-19
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 2022-06-18
    • 2021-02-04
    • 2019-08-28
    相关资源
    最近更新 更多