知识点一:过滤器
与data同级,使用filters对象来写过滤器函数,在原文内容中用管道符" | "引入过滤函数,打个比方:佩奇是猪,猪猪侠也是猪,我们想在输出的时候注明它们是猪,除了直接写还有什么办法呢?当然是过滤器啦@_@,哈哈,来示例:
//页面代码
<template>
<div class="">
<template v-for="nam in name">
{{nam|zhu}}
</template>
</div>
</template>
//数据及过滤器
data () {
return {
name:["佩奇","猪猪侠"]
}
},
filters:{
zhu:function(value){
if(!value) return;
return value +"-这是猪哦~"
}
}
知识点二:axios网络请求
axios是基于promise的http库,使用时需要先安装axios插件,指令:
npm install axios --save //在项目内安装
然后启动vue项目,这就完了吗?不,并没有,还需要在vue全局挂载,在main.js文件中
import Axios from "axios"
Vue.prototype.$axios=Axios
将axios插件引入进来,在vue文件中data同级使用生命周期函数来请求,是mounted(){}关于axios的详细文档可以去网站https://www.kancloud.cn/yunye/axios/234845查看
来个示例,由于没有可请求的地址,比着学习视频写的,但是不能访问
mounted(){
this.$axios.get("http://www.wwtliu.com/sxtstu/blueberrypai/getChengpinInfo.php")
.then(res=>{console.log(res.data)})
.catch(error=>{console.log(error)}
)
}
因为是我们引入的插件,所以使用时,需要用this.$axios来引入,参数可以直接加在后面,也可以get("url",{params:{参数}})
post请求:
import qs from 'qs'
export default {
name: 'filterDemo',
components:{
},
data () {
return {
}
},
mounted(){
this.$axios.post("http://www.wwtliu.com/sxtstu/blueberrypai/login.php",qs.stringify({
user_id:"iwen@qq.com",
password:"iwen123",
verfication_code:"crfvw"
}))
.then(res=>{console.log(res.data)})
.catch(error=>{console.log(error)}
)
}
这里引入ps工具转换参数格式(在user_id:"iwen@qq.com",password:"iwen123", verfication_code:"crfvw"格式与user_id=iwen@qq.com& password=iwen123&verfication_code=crfvw间转换)有时候参数书写正确,但访问时报参数缺失问题,这个问题也可以放到全局,用拦截器进行统一处理,拦截器在main.js文件中设置,代码示例:
import Axios from "axios"
import qs from "qs"
Vue.config.productionTip = false
Axios.defaults.baseURL = 'http://www.wwtliu.com'; //配置全局访问的网址
Axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
if(config.method==="post"){
config.data=qs.stringify(config.data)
}
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
这样在发送请求前请求拦截器提前处理,那么接收数据时的拦截器呢,来示例:
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
if(!response.data){
return {
mag:'数据为空'//处理返回的数据
}
}
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
这样在前端接收到数据时响应拦截器可以先处理数据
知识点三:跨域处理
这里需要修改配置文件config文件夹下的index.js文件,其中 大约13行的proxyTable属性,在其里面添加配置:
proxyTable: {
'/doubai':{
target:'http://api.douban.com',
pathRewriite:{
'^/doubai':''
},
changeOrigin:true
}
},
//这其中需要根据不同需求修改的是第二行‘/’后面的内容,target后面的链接,‘^/’后面的名称
为了方便书写呢,可以在main.js文件做全局引用,形式为:
Vue.prototype.HOST="/doubai"
这里的doubai不是固定的 ,这样就可以在不同的文件中通过
this.HOST
使用该链接,这里的doubai不是固定的 ,使用方法如下
var url=this.HOST+'/v2/movie/top250';
this.$axios({
method:'get',
url:url
}).then(res=>{
console.log(res.data);
}).catch(error=>{
console.log(error);
})
一段时间后的补充:注意!注意!注意!重要的事情说三遍!
修改完跨域配置后一定要重启,一定要重启,一定要重启!我在后来写代码过程中跨域时没重启,困扰了我一下午<-_->