vue组件不显示数据

时间:2019-07-11 05:28:54

标签: laravel vue.js components

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>

3 个答案:

答案 0 :(得分:2)

尝试下面的代码,我对需要更改的位进行了注释。

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
        });

答案 1 :(得分:0)

    <div id="app">
       <router-view>
          <posts></posts>
       </router-view>
    </div>

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


    data: function() {
                return {
                    posts:[],
                }
            },




//app.js

import Vue from 'vue';

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




Vue.component('posts',
  require('./components/Posts.vue'));

const app = new Vue({
    el: '#app'
});

答案 2 :(得分:0)

` 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'));