主要操作技能:
1. 通过https://github.com/ 查找 vue-resource插件
2 .使用vue-resource请求数据的步骤:.
2.1)需要安装 vue-resource模块 ,注意加上--save
npm install vue-resource --save/cnpm install vue-resource --save
2.2) 在main.js中引用
import VueResource from 'vue-resource'
Vue.use(VueResource);
2.3)在组件中直接使用
this.$http.get(地址).then(function(){});
编写代码:
Home.vue
<template>
<!--所以的内容多要被根节点包含起来 -->
<div id="home">
{{msg}}
<button @click="getData()">请求数据</button><br /><br />
<ul>
<li v-for="item in list">
{{item.aid}}--{{item.title}}
</li>
</ul>
</div>
</template>
<script>
/**
* 请求数据模板
* https://github.com/ 查找
* >cnpm install vue-resource --save
* vue-resource 官方提供的一个插件
*
* axios
*
* fetch-jsonp
*
*/
export default {
data() { //数据
return {
msg: '我是首页组件',
list: [] //存放请求数据
}
},
methods: { //方法
getData() {
//请求数据地址
var url = 'http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1';
//get方式
// this.$http.get(url).then(function(response) {
// console.log(response);
// },
// function(err) {
// console.log(err);
// })
//修改成=>
this.$http.get(url).then((response) => {
console.log(response);
//this指向当前对象
this.list = response.body.result;
},
function(err) {
console.log(err);
})
}
},
mounted() { //生命周期函数 (直接初始化数据到页面了哦!)
this.getData();
}
}
</script>
main.js
import Vue from 'vue'
import App from './App.vue'
import VueResource from 'vue-resource'
Vue.use(VueResource);
new Vue({
el: '#app',
render: h => h(App)
})
App.vue
<template>
<div id="app">
<!--//3.使用组件-->
<v-home></v-home>
</div>
</template>
<script>
import Home from './components/Home.vue' //1.引入组件
export default {
name: 'app',
data() { //业务逻辑的数据
return {
msg: 'hello'
}
},
components: { //2.挂载组件
'v-home': Home
}
}
</script>
效果:
单击按钮,就能获得查询出来的数据
直接初始化数据到页面(用到生命周期函数 mounted(){})