您的位置:首页 > Web前端 > Vue.js

vue中组件之间使用axios传值

2019-05-24 17:56 453 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/qq_43339643/article/details/90520833

1.使用axios传值的首先可以通过npm安装

npm install axios from 'axios'

2.安装成功后启动项目

使用语句 npm run dev
接下来进入项目中,在main.js里面引入并实例化

import axios from 'axios'
Vue.prototype.axios=axios

3.使用方法

我找了一个开源的api做了新闻列表接入,如下

html部分:

<ul>
<li v-for="(item,key) in list" style="list-style:none;">
<router-link :to="'/newscontent/'+(item.aid)">{{item.title}}</router-link>
</li>
</ul>

调用部分:
tips:在.then()里面最好使用ES6的箭头函数,目的是统一方法内外的两个this对象,使外面的this对象等于指向里面的this对象

methods: {
getDate() {
var api =
"http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1";
this.axios.get(api).then(
respon => {
this.list = respon.data.result;
},
error => {}
);
}
},
mounted() {
this.getDate();
}

接收部分
1:当然,首先要使用路由布置传递方式,这里我使用的是动态路由匹配
在index.js文件中这样写

{
path: '/newscontent/:aid',//动态路由匹配
name: 'newscontent',
component: Newscontent ,
},

2:在要接受的组件中这样写

<template>
<div>
<div v-for="(item,key) in msg">
<div v-html="item.content"></div>
</div>
</div>
</template>
<script>
export default {
data(){
return{
msg:[]
}
},
methods:{
getDate(value){
var api='http://www.phonegap100.com/appapi.php?a=getPortalArticle&aid='+value
this.axios.get(api).then((respon)=>{

this.msg=respon.data.result
},(error)=>{

})
}
},
mounted(){
var aid=this.$route.params.aid;//这里是动态路由接受参数的方式
this.getDate(aid)
}
}
</script>

写的不好或者不对的地方,欢迎指正

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: