【问题标题】:vue component doesn't show datavue 组件不显示数据
【发布时间】:2019-11-20 18:09:58
【问题描述】:

Axios 加载数据没有任何问题,不显示任何数据,Laravel Mix 构建没有错误。

我有以下代码:

index.html(正文)

<div id="app">
    <posts></posts>
</div>

在 app.js 我使用这个:

import Vue from 'vue';

// global declare axios
window.axios = require('axios');

import Posts from './components/Posts';
Vue.component('posts', Posts);

new Vue({
    el: '#app',

    props: {
        posts:[{
            userId: [Number],
            id: [Number],
            title: [String, Number]
        }]
    }
});

在 Posts.vue 组件中,我创建了一个模板和一个在安装时加载数据的脚本:

<template>
    <ul>
        <li v-for="post in posts" v-text="post.title"></li>
    </ul>
</template>

<script>
    export default {


        data: function() {
            return {
                posts: null,
            }
        },

        // when stuff is loaded (document ready)
        mounted: function() {

            // use placeholder data for tests, capture asynchronous data from site using this.
            axios.get('https://jsonplaceholder.typicode.com/posts')
                .then(response => this.posts = response.posts)
                .catch(error => this.posts = [{title: 'No posts found.'}])
                .finally(console.log('Posts loading complete'));
        },
    }
</script>

所以数据应该显示为一个ul列表:

<ul>
  <li>
     title
  </li>
  <li>
     title
  </li>
  <li>
     title
  </li>
</ul>

【问题讨论】:

    标签: laravel vue.js components


    【解决方案1】:

    试试下面的代码,我已经在需要更改的位上制作了 cmets。

    data() {
        return {
            posts: [] // this should be an array not null
        };
    },
    
    // you can do this on created instead of mounted
    created() {
        axios.get('https://jsonplaceholder.typicode.com/posts')
            .then(response => {
                this.posts = response.data; // add data to the response
            });
    

    【讨论】:

    • 这成功了,谢谢!创建或安装的作品 - 最佳做法是什么?教程倾向于使用mounted函数。
    • Created 应该没问题,如果你正在处理依赖于 DOM 中准备好的元素的东西,请使用mounted。请不要忘记将问题标记为已回答
    【解决方案2】:
    ` Here "this.post" not take it has instance in axios call.So you have follow like this. `
    

    var vm=this;

    axios.get('https://jsonplaceholder.typicode.com/posts') .then(response => vm.posts = response.posts) .catch(error => vm.posts = [{title: 'No posts found.'}]) .finally(console.log('Posts loading complete'));

    【讨论】:

    • 谢谢,但您的建议并没有解决问题,仍然没有数据。 确实得到了更新,但只是一个空的
      猜你喜欢
      • 2016-11-30
      • 2021-05-13
      • 2018-10-27
      • 2019-11-19
      • 1970-01-01
      • 1970-01-01
      • 2018-05-02
      • 1970-01-01
      • 2019-08-15
      相关资源
      最近更新 更多