vue组件获取本地json,获取json什么的都没有问题,也没有报错,测试数据存放在static文件夹里


问题是json里面的数据渲染不出来,尝试过axios和jq的方法
template:
<template>
<div>
<div class="list">
<ul>
<li v-for="list in textData">
<h2>{{list.title}}</h2>
</li>
</ul>
</div>
</div>
</template>
js:
<script>
import axios from 'axios';
import $ from 'jquery';
export default {
name: 'list',
data() {
return {
loading: false,
textData: {}
}
},
created() {
this.getData();
},
components: {
mobileHeader
},
methods: {
getData() {
// axios.get('../../static/20190706.json', {}).then((response) => {
// this.textData = response.data;
// }, response => {
// console.log('error');
// });
$.ajax({
type: 'get',
url: '../../static/20190706.json',
async: true,
success: (data) => {
this.textData = this.textData.concat(data.stories);
}
})
}
}
}
</script>
当然main.js里也添加了这两句
import axios from 'axios';
Vue.prototype.$http = axios;
期间看过其他人写的代码,感觉自己的思路是对的,只是不知缺少了些什么,望大神不吝赐教。
这个问题解决了,最后还是采用axios的方法
首先是response.data是个字符串,而且还不是json字符串,所以要把response.data用JSON.stringify()方法转换一下:
var storiesList = JSON.stringify(res.data);
然后再转为json对象:
this.textData = JSON.parse(storiesList);
这些都源于一个报错:Unexpected token o in JSON at position 1
参考博客:https://blog.csdn.net/qq_4199...
页面渲染的地方也不能直接是v-for="list in textData",应该是某个键值:
或者直接在storiesList获取stories键值:
页面渲染地方做出的变动: