Vue-10-ajax-引入ajax
2018-10-21 本文已影响0人
OrangeQjt
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id='app'>
<!--1.-->
<router-link to='/home'>首页</router-link>
<router-link to='/user'>用户页</router-link>
<!-- 盛放链接对应的内容-->
<router-view></router-view>
</div>
<script src='../vue.js/vue.js'></script>
<script src='../vue-router/vue-router.js'></script>
<script src='../axios.js/axios.js'></script>
<script>
//2.创建组件
var Home={
template:`
<h1>这是首页</h1>
`
}
var User={
template:`
<div>
<h1>这是用户页</h1>
<table border=1 cellspacing=0>
<thead>
<tr>
<th>编号</th>
<th>品名</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
</tr>
</thead>
<tbody>
<tr v-for="value in list">
<td>{{value.num}}</td>
<td>{{value.pname}}</td>
<td>{{value.price}}</td>
<td>{{value.count}}</td>
<td>{{value.sub}}</td>
</tr>
</tbody>
</table>
</div>
`,
data:function(){
return{
list:null
}
},
mounted:function(){
var self=this;
axios({
method:"get",//get post 获取方法
url:'fruit.json' //路径
}).then(function(resp){//请求成功
console.log(resp.data)
self.list=resp.data;
}).catch(function(err){//请求失败
console.log(err)
})
}
}
//3.配置路由
const routes=[
{path:'/',component:Home},
{path:'/home',component:Home},
{path:'/user',component:User}
]
//4.创建路由实例
const router=new VueRouter({
routes:routes,
linkActiveClass:'active'
})
//5.路由实例挂载到vue实例上
new Vue({
el:'#app',
router:router
})
</script>
</body>
</html>
2.引入ajax:
1.>下载axios.js
import axios from 'axios'
export default{
data:function(){
return{txt:null} //不确定数据类型,所以将txt的值设为空值;
},
methods:{},
mounted:function(){
var self=this;
axios({
method:'get' //请求方法
url:'../../static/ .json'
}).then(function(aaa){
console.log(aaa.data)
self.txt=aaa.data //单独的aaa.data无法加载,需将数据赋值给txt到页面
}).catch(function(bbb){
console.log(bbb)
})
}
}