首页 > 解决方案 > 在未呈现 bootstrap-vue 的 vue.js CLI 应用程序中

问题描述

我有一个使用 vue-CLI 制作的应用程序,包括 bootstrap-vue。在我的App.vue中,我使用 axios 来获取一些示例 JSON 数据。使用这个带有 html-tags (UL, LI) 的简单代码,可以显示数据:

 <p v-if="loading">Loading...</p>
    <ul v-else>
      <li v-for="(value, key) in post" :key="key">
        {{ key }} : {{ value }}
      </li>
    </ul>

这是输出: 在此处输入图像描述

使用代码,使用引导标签和相同的数据,数据没有显示在列表项中,似乎是一个损坏的渲染。

   <b-list-group >
      <b-list-group-item
        href="#"
        class="flex-column align-items-start"
        v-for="result in post"
        v-bind:key="result.userId"
      >
        <div class="d-flex w-100 justify-content-between">
          <h6 class="mb-1">{{ result.title }}</h6>
          <small>{{ result.id }}</small>
        </div>

        <p class="mb-1">{{ result.body }}</p>

      </b-list-group-item>
    </b-list-group> 

这是输出: 在此处输入图像描述

生成了 html 代码,但标签之间没有数据。element-Inspector (chrome) 显示...

在此处输入图像描述

有什么问题?有人有想法吗?请帮忙。

这是我的main.js

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import JQuery from 'jquery'
let $ = JQuery

import BootstrapVue from 'bootstrap-vue'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'

Vue.use(BootstrapVue)

Vue.use(VueRouter);

Vue.prototype.$log = console.log;

new Vue({
  el: '#app',
  render: h => h(App)
})

这是我在Vue.app中的脚本:

<script>
const productAPI =
  "http://www.m.myapp2go.de/services/getnewsliste.php?typ=news&id=10024";

import axios from "axios";
import Counter from "./Counter";

export default {
  name: "app",
  data() {
    return {
      msg: "Vue.js Template Test App",
      loading: false,
      post: null,
      results: null,
      error: ""
    };
  },
  components: {
    "my-counter": Counter
  },
  created: function() {
    this.loading = true;
    axios
      .get("https://jsonplaceholder.typicode.com/posts/1")
      .then(res => {
        this.loading = false;
        this.post = res.data;
      })
      .catch(err => {
        this.loading = false;
        this.error = err;
      });
  },
  methods: {
    log(message) {
      console.log(message);
    }
  }
};
</script>

标签: javascriptvue.jsaxiosbootstrap-vue

解决方案


那是因为 apihttps://jsonplaceholder.typicode.com/posts/1返回一个对象而不是数组。如果您改为调用https://jsonplaceholder.typicode.com/posts,您将检索对象数组并且您的代码应该可以工作。

但是,如果您调用的 API 点是您想要的,这意味着您正在迭代对象键。您需要将 API 的结果插入到数组中或删除v-forpost直接使用。

axios
  .get("https://jsonplaceholder.typicode.com/posts/1")
  .then(res => {
    this.loading = false;
    this.post = [res.data];
  })
  .catch(err => {
    this.loading = false;
    this.error = err;
  });

或者

<b-list-group >
  <b-list-group-item
     href="#"
     class="flex-column align-items-start"
   >
     <div class="d-flex w-100 justify-content-between">
       <h6 class="mb-1">{{ post.title }}</h6>
       <small>{{ post.id }}</small>
     </div>
   <p class="mb-1">{{ post.body }}</p>
 </b-list-group-item>
</b-list-group> 

推荐阅读