vue-cli项目创建
1.全局安装vue-cli(注:要求node.js版本是8+)
cnpm install -g @vue/cli
or
yarn global add @vue/cli
检测安装:vue -V
2.创建项目:vue create 项目名称(可以写.代表在本文件夹创建)
这里如果你是第一次使用脚手架进行项目创建的话,是只有两项提示。
第一项是默认配置,我们一般选择第二项自定义配置进行项目构建。
我们可以自由的选择哪些配置,按键盘上下键进行选中,安装。
选中哪一个,通过键盘空格键确定,所有的都选择完毕后,按键盘的Enter键进行下一步。
文件名后缀是.vue的为单文件组件,包含三部分:template script style。内部配置wepack的vue-loader来去解析处理解析以.vue为后缀名的单文件组件。
- style标签 加上scoped属性,css局部生效 ,想要影响子组件可以用>>>穿透,sass预处理器用/deep/;
- style标签 加上lang=“scss”,支持scss。
如果配置了eslint(严格语法检查),想要关闭它,那么需要创建vue.config.js文件,采用如下代码:
module.exports = {
devServer: {
overlay: {
warnings: false,
errors: false
}
},
lintOnSave:false //直接关闭eslint检查
}
在这个文件夹还可以进行proxy代理配置、alias别名配置和打包路径。
module.exports = {
//打包路径
publicPath: '/vue-demo',
devServer: {
overlay: {
warnings: false,
errors: false
},
//proxy代理配置,上传服务器的
proxy: {
//表示要匹配请求的url中,全部'http://服务器网址:3000/api'
'/api': {
target: 'http://服务器网址:3000',//代理接口
changeOrigin:true,//是否跨域
pathRewrite:{
"^/api":""//重写这个路径为'http://服务器网址:3000'
}
}
}
},//客户端关闭了
lintOnSave:false,
//alias别名配置
configureWebpack: {
resolve: {
alias: {
'assets': '@/assets',
'con': '@/components',
'views': '@/views',
}
}
} //直接关闭eslint检查
}
vue-cli脚本架中,请求本地资源,数据放在public文件夹下,可以不配置。
数据请求
1.vue-resource请求
直接引用地址https://cdn.bootcdn.net/ajax/libs/vue-resource/1.3.4/vue-resource.min.js
就可以在vue实例/组件 上面绑定一个$http的一个属性。
//从vue2.0开始,将不对vue-resource进行维护,推荐使用axios
methods:{
get(){
this.$http.get("./json/temp.json").then(res=>{
console.log(res.data.books)
this.books = res.data.books
})
}
}
2.fetch请求
//请求的上面的public文件夹下的json文件夹下的数据
//get方法
get(){
fetch("/json/temp.json").then(res=>res.json()).th en(res=>{console.log(res)})
fetch("/json/temp.json").then(res=>res.text()).then(res=>{console.log(res)})
}
//post方法
post(){
fetch("http://localhost:3000/add",{
method:"post",
headers:{
"Content-Type":"application/x-www-form-urlencoded"
// "Content-Type":"application/json"
},
// body:JSON.stringify({
// username:"张三",
// age:10
// })
body:"name=李四&password=111" }).then(res=>res.json()).then(res=>console.log(res))
}
3.axios请求
// get
axios.get("json/test.json?name=zhangsan&age=10").then(res=>{
// res.data 才是真正的后端数据
console.log(res.data.data.films)
this.datalist = res.data.data.films
})
//post -1- x-www-form-urlencode
axios.post("json/test.json","name=zhangsan&age=10").then(res=>{
console.log(res.data)
})
//post -2- application/json
axios.post("json/test.json",{
name:"zhangsan",
age:100
}).then(res=>{
console.log(res.data)
})