[英]vue component doesn't show data
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>
尝试下面的代码,我对需要更改的位进行了注释。
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
});
` 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'));
<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'
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.