-
今日重点 下一篇 vue(四)
* vue组件的使用
* 组件间通信
* vue-router使用
* vue-resource发起http请求
* axios - vue单文件方式 xxx.vue
- 1:准备好配置文件 package.json(包描述文件&& 封装命令npm run dev) + webpack.config.js文件(打包的配置文件)
2:创建index.html(单页应用的页)
3:创建main.js(入口文件)
4:引入vue和相关的文件xxx.vue
5:new Vue(options)
6:options(选项):
- data
- methods
- components(组件内声明子组件)
- props
7:实例:
- 在组件内(xxx.vue)中的this
- new Vue()
- 事件
+ this.$on(事件名,回调函数(参数))
+ this.$emit(事件名,数据)
+ this.$once(事件名,回调函数(参数)) 就触发一次
+ this.$off(事件名); 取消事件
8:全局
- Vue.component('组件名',组件对象) 在哪里都可以使用
9: 组件传值
- 父传子: 属性作为参数
+ 常量 title="xxx" 子组件声明接收参数 props:['xxx']
+ 变量 :title="num" 子组件声明接收参数 props:['xxx']
- 子传父: vuebus(只能是同一辆车)
+ 先停车到父组件,On一下
+ 再开车到子组件,如果需要的话,emit一下,触发上述时间的回调函数
- 过滤器
* content | 过滤器,vue中没有提供相关的内置过滤器,可以自定义过滤器
* 组件内的过滤器 + 全局过滤器
- 组件内过滤器就是options中的一个filters的属性(一个对象)
+ 多个key就是不同过滤器名,多个value就是与key对应的过滤方式函数体
- `Vue.filter(名,fn)`
* 输入的内容帮我做一个反转
* 例子:父已托我帮你办点事
* 总结
- 全局 :范围大,如果出现同名时,权利小
- 组件内: 如果出现同名时,权利大,范围小 - 过滤器示例
- 目录结构
-
app.vue
<template> <div> <!-- 请输入内容 <input type="text" name="" v-model="text"> 显示:{{text | myFilter}} --> <!-- 测试组件的范围 --> <sub-vue></sub-vue> <div></div> </div> </template> <script> import SubVue from './sub.vue'; export default { filters:{ myFilter:function(value){ //value 就是-> text //输入的内容帮我做一个反转 //转换成数组,反转数组,转换成字符串 return value.split('').reverse().join(''); } }, data(){ return { text:'' } }, components:{ subVue:SubVue } } </script> <style> </style>
3.index.html
<html> <head> <meta charset="UTF-8"> <title>01_过滤器</title> </head> <body> <div id="app"></div> </body> </html>
4.main.js
//引入vue import Vue from 'vue'; //引入app.vue import App from './app.vue'; //创建全局过滤器 Vue.filter('myFilter', function(value) { return '我是全局过滤器'; }); //new Vue new Vue({ el: '#app', render: c => c(App) })
5.sub.vue
<template> <div> sub.vue {{'大家好,我是sub' | myFilter}} </div> </template> <script> export default { data(){ return { } } } </script> <style> </style>
6.package.json
{ "name": "webpack_class", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev":".\\node_modules\\.bin\\webpack-dev-server --inline --hot --open --port 8888", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "autoprefixer-loader": "^3.2.0", "babel-core": "^6.25.0", "babel-loader": "^7.1.1", "babel-plugin-transform-runtime": "^6.23.0", "babel-preset-es2015": "^6.24.1", "css-loader": "^0.28.4", "file-loader": "^0.11.2", "less": "^2.7.2", "less-loader": "^4.0.5", "style-loader": "^0.18.2", "url-loader": "^0.5.9", "vue-loader": "^13.0.4", "vue-template-compiler": "^2.4.2", "webpack": "^3.4.1", "webpack-dev-server": "^2.6.1" }, "dependencies": { "html-webpack-plugin": "^3.2.0", "vue": "^2.4.2" } }
7.webpack.config.js
const htmlWebpackPlugin = require('html-webpack-plugin'); const path = require('path') module.exports = { entry:{ //main是默认入口,也可以是多入口 main:'./src/main.js' }, //出口 output:{ filename:'./build.js', //指定js文件 path: path.join(__dirname,'dist') //最好是绝对路径 //代表当前目录的上一级的dist }, module:{ //一样的功能rules: webpack2.x之后新加的 loaders:[ //require('./a.css||./a.js') {test:/\.css$/, loader:'style-loader!css-loader', //顺序是反过来的2!1 }, { test:/\.(jpg|svg|png|gif)$/, loader:'url-loader?limit=4096&name=[name].[ext]', //顺序是反过来的2!1 //[name].[ext]内置提供的,因为本身是先读这个文件 // options:{ // limit:4096, // name:'[name].[ext]' // } },{//处理ES6的js test:/\.js$/, loader:'babel-loader', //排除 node_modules下的所有 exclude:/node_modules/, options:{ presets:['es2015'],//关键字 plugins:['transform-runtime'],//函数 } },{//解析vue test:/\.vue$/, loader:'vue-loader',//vue-template-compiler是代码上的依赖 } ] }, plugins:[ //插件的执行顺序是依次执行的 new htmlWebpackPlugin({ template:'./src/index.html', }) //将src下的template属性描述的文件根据当前配置的output.path,将文件移动到该目录 ] }
8.进入到01_fitter 目录下,进入cmd,执行npm install 安装package.jaon里面的模块产生node_modules目录。然后执行 npm run dev ,页面效果如下:
-
过滤器(二 )
-
目录与如上
-
app.vue
<template> <div> <sub-vue ref="sub"></sub-vue> <!-- <div ref="myDiv"> {{text}} </div> --> </div> </template> <script> import SubVue from './sub.vue'; export default { data(){ return { text:'123' } }, components:{ subVue:SubVue }, //组件创建后, 数据已经完成初始化,但是DOM还未生成 created(){ // 事件的处理函数(created) console.log('created:',this.$refs.myDiv);//获取不到 }, //数据装载DOM上后,各种数据已经就位,将数据渲染到DOM上,DOM已经生成 mounted(){ // console.log('sub:',this.$refs.sub.$el); //获取组件对象,并获取到其的DOM对象 this.$refs.sub.$el.innerHTML = '嘻嘻'; // console.log('mounted:',this.$refs.myDiv); // 涉及DOM类的操作 // this.$refs.myDiv.innerHTML = '哈哈呵呵'; // 涉及到数据的操作 this.text = '嘻嘻呵呵' } } </script> <style> </style>
-
index.html
<html> <head> <meta charset="UTF-8"> <title>01_过滤器</title> </head> <body> <div id="app"></div> </body> </html>
-
main.js
//引入vue import Vue from 'vue'; //引入app.vue import App from './app.vue'; //new Vue new Vue({ el: '#app', render: c => c(App) })
-
sub.vue
<template> <div> sub.vue {{'大家好,我是sub' }} </div> </template> <script> export default { data(){ return { } } } </script> <style> </style>
-
package.json和webpack.config.js不变,进入到目录下,进入cmd,执行npm install 安装package.jaon里面的模块产生node_modules目录。然后执行 npm run dev ,页面效果如下::
-
获取DOM元素
* 救命稻草, 前端框架就是为了减少DOM操作,但是特定情况下,也给你留了后门
* 在指定的元素上,添加ref="名称A"
* 在获取的地方加入 this.$refs.名称A
- 如果ref放在了原生DOM元素上,获取的数据就是原生DOM对象
+ 可以直接操作
- 如果ref放在了组件对象上,获取的就是组件对象
+ 1:获取到DOM对象,通过this.$refs.sub.$el,进行操作
- 对应的事件
+ created 完成了数据的初始化,此时还未生成DOM,无法操作DOM
+ mounted 将数据已经装载到了DOM之上,可以操作DOM -
mint-ui
* 组件库
* 饿了么出品,element-ui 在PC端使用的
* 移动端版本 mint-ui
* https://mint-ui.github.io/#!/zh-cn
* 注意:
- 如果是全部安装的方式
+ 1:在template中可以直接使用组件标签
+ 2:在script中必须要声明,也就是引入组件对象(按需加载) -
mint-ui案例
-
目录结构
-
app.vue
<template> <div> <mt-header title="多个按钮"> <mt-button icon="back">返回</mt-button> <mt-button>关闭</mt-button> <mt-button icon="more" slot="right"></mt-button> </mt-header> <button @click="handleClose">显示弹出框</button> <mt-switch v-model="value"></mt-switch> <mt-swipe :auto="4000"> <mt-swipe-item>1</mt-swipe-item> <mt-swipe-item>2</mt-swipe-item> <mt-swipe-item>3</mt-swipe-item> </mt-swipe> </div> </template> <script> //在js部分所有变量都是模块作用域 //如果需要使用就必须引入 import { Toast } from 'mint-ui'; export default { data(){ return { text:'123', value:false } }, methods:{ handleClose(){ Toast('提示信息'); } } } </script> <style> </style>
-
index.html
<html> <head> <meta charset="UTF-8"> <title>01_过滤器</title> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> </head> <body> <div id="app"></div> </body> </html>
-
main.js
//引入vue import Vue from 'vue'; //引入app.vue import App from './app.vue'; //引入mint-ui import MintUi from 'mint-ui'; //引入样式 import '../node_modules/mint-ui/lib/style.css'; //安装插件 Vue.use(MintUi); //use实际操作 //1: 组件库,在内部注册了各种全局组件 //2: 插件, 挂载属性,为了方便this.可以使用到其功能 //new Vue new Vue({ el: '#app', render: c => c(App) })
-
package.json和webpack.config.js不变,进入03 目录下,进入cmd,执行npm install ,如果没有mint-ui的话要安装mint-ui,命令为npm install mint-ui, 安装package.jaon里面的模块产生node_modules目录。然后执行 npm run dev ,页面效果如下:
-
vue-router
* 前端路由 核心就是锚点值的改变,根据不同的值,渲染指定DOM位置的不同数据
* ui-router:锚点值改变,如何获取模板?ajax、
* vue中,模板数据不是通过ajax请求来,而是调用函数获取到模板内容
* 核心:锚点值改变
* 以后看到vue开头,就知道必须Vue.use
* vue的核心插件:
- vue-router 路由
- vuex 管理全局共享数据
* 使用方式
- 1:下载 `npm i vue-router -S`
- 2:在main.js中引入 `import VueRouter from 'vue-router';`
- 3:安装插件 `Vue.use(VueRouter);`
- 4:创建路由对象并配置路由规则
+ `let router = new VueRouter({ routes:[ {path:'/home',component:Home} ] });`
- 5:将其路由对象传递给Vue的实例,options中
+ options中加入 `router:router`
- 6:在app.vue中留坑 ` <router-view></router-view>` -
命名路由
* 需求,通过a标签点击,做页面数据的跳转
* 使用router-link标签
- 1:去哪里 `<router-link to="/beijing">去北京</router-link>`
- 2:去哪里 `<router-link :to="{name:'bj'}">去北京</router-link>`
+ 更利于维护,如果修改了path,只修改路由配置中的path,该a标签会根据修改后的值生成href属性 -
参数router-link
* 在vue-router中,有两大对象被挂载到了实例this
* $route(只读、具备信息的对象)、$router(具备功能函数)
* 查询字符串
- 1:去哪里 `<router-link :to="{name:'detail',query:{id:1} } ">xxx</router-link>`
- 2:导航(查询字符串path不用改) `{ name:'detail' , path:'/detail',组件}`
- 3:去了干嘛,获取路由参数(要注意是query还是params和对应id名)
+ `this.$route.query.id`
* path方式
- 1:去哪里 `<router-link :to="{name:'detail',params:{name:1} } ">xxx</router-link>`
- 2:导航(path方式需要在路由规则上加上/:xxx)
- `{ name:'detail' , path:'/detail/:name',组件}`
- 3:去了干嘛,获取路由参数(要注意是query还是params和对应name名)
+ `this.$route.params.name` -
vue-router案例
-
目录结构
-
app.vue
<template> <div> <!-- 留坑,非常重要 --> <router-view></router-view> </div> </template> <script> export default { data(){ return { } } } </script> <style> </style>
-
home.vue
<template> <div> 我是主页 </div> </template> <script> export default { data(){ return { } } } </script> <style> </style>
-
index.html
<html> <head> <meta charset="UTF-8"> <title>Document</title> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> </head> <body> <div id="app"></div> </body> </html>
-
main.js
-
//引入一堆 import Vue from 'vue'; import VueRouter from 'vue-router'; //主体 import App from './components/app.vue'; import Home from './components/home.vue' //安装插件 Vue.use(VueRouter); //挂载属性 //创建路由对象并配置路由规则 let router = new VueRouter({ //routes routes: [ //一个个对象 { path: '/home', component: Home } ] }); //new Vue 启动 new Vue({ el: '#app', //让vue知道我们的路由规则 router: router, //可以简写router render: c => c(App), })
-
package.json和webpack.config.js不变,进入到目录下,进入cmd,执行npm install 安装package.jaon里面的模块产生node_modules目录。然后执行 npm run dev ,页面效果如下:
记住,在main.js里import了什么就要安装什么,所以别忘了安装vue-router
-
vue-router 和参数案例
-
目录结构
-
app.vue
<template> <div> <div class="h">头部</div> <!-- 留坑,非常重要 --> <router-view class="b"></router-view> <div class="f">底部</div> </div> </template> <script> export default { data(){ return { } } } </script> <style scoped> .h{ height: 100px; background-color: yellowgreen; } .b{ height: 100px; background-color: skyblue; } .f{ height: 100px; background-color: hotpink; } </style>
-
detail.vue
<template> <div> 详情 </div> </template> <script> export default { data(){ return { } },//DOM还未生成 created(){ //获取路由参数 //vue-router中挂载两个对象的属性 //$route(信息数据) $router (功能函数) console.log(this.$route.query); console.log(this.$route.params); }//已经将数据装载到页面上去了,DOM、已经生成 ,mounted(){ } } </script> <style> </style>
-
list.vue
<template> <div> 查询字符串列表: <ul> <li v-for="(hero,index) in heros" :key="index"> {{hero.name}} <!-- 1:去哪里 /detail?id=12 --> <router-link :to="{name:'detail',query:{id:index} }">查看</router-link> </li> </ul> <!-- path列表: <ul> <li v-for="(hero,index) in heros" :key="index"> {{hero.name}} 1:去哪里 /detail/12 <router-link :to="{name:'detail',params:{id:index} }">查看</router-link> </li> </ul> --> </div> </template> <script> export default { data(){ return { heros:[{ name:'李白' },{ name:'王昭君' }] } } } </script> <style> </style>
-
index.html
<html> <head> <meta charset="UTF-8"> <title>Document</title> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> </head> <body> <div id="app"></div> </body> </html>
-
main.js
//引入一堆 import Vue from 'vue'; import VueRouter from 'vue-router'; //主体 import App from './components/app.vue'; //路由切换页面 import List from './components/list.vue' import Detail from './components/detail.vue' //安装插件 Vue.use(VueRouter); //挂载属性 //创建路由对象并配置路由规则 let router = new VueRouter({ //routes routes: [ //一个个对象 { name: 'list', path: '/list', component: List }, //以下规则匹配 /detail? xxx = xx & xxx = xxx 多少个查询字符串都不影响 //查询字符串path不用改 { name: 'detail', path: '/detail', component: Detail }, // // {name:'detail',params:{id:index} } -> /detail/12 { name: 'detail', path: '/detail/:id', component: Detail } ] });
-
package.json和webpack.config.js不变,进入到目录下,进入cmd,执行npm install 安装package.jaon里面的模块产生node_modules目录。然后执行 npm run dev ,页面效果如下:
记住,在main.js里import了什么就要安装什么,所以别忘了安装vue-router
- 音乐和电影案例
- 目录结构
-
app.vue
<template> <div> <div class="h">头部</div> <!-- 留坑,非常重要 --> <router-view class="b"></router-view> <div class="f">底部</div> <button @click="goMuisc">跳转到音乐</button> <button @click="testParams">测试编程导航传递参数</button> </div> </template> <script> export default { data(){ return { } },methods:{ goMuisc(){ this.$router.push('/music'); }, testParams(){ //查询字符串的方式 /music?id=1&name=2 this.$router.push({ name:'music',query:{ id:1,name:2 } }); } } } </script> <style scoped> .h{ height: 100px; background-color: yellowgreen; } .b{ height: 100px; background-color: skyblue; } .f{ height: 100px; background-color: hotpink; } </style>
-
movie.vue
<template> <div> 我是电影 <button @click="goback">向上一页</button> </div> </template> <script> export default { data(){ return { } },methods:{ goback(){ this.$router.go(-1); //-1上一次记录 } } } </script> <style> </style>
-
music.vue
<template> <div> 我是音乐 <button @click="goMovie">跳转到电影</button> <button @click="goback">向上一页</button> <button @click="go">向下一页</button> </div> </template> <script> export default { data(){ return { } },methods:{ goMovie(){ this.$router.push({ name:'movie' }) }, goback(){ this.$router.go(-1); //后退 } ,go(){ this.$router.go(1);//前进 } } } </script> <style> </style>
-
index.html
<html> <head> <meta charset="UTF-8"> <title>Document</title> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> </head> <body> <div id="app"></div> </body> </html>
-
main.js
//引入一堆 import Vue from 'vue'; import VueRouter from 'vue-router'; //主体 import App from './components/app.vue'; //路由切换页面 import Music from './components/music.vue' import Movie from './components/movie.vue' //安装插件 Vue.use(VueRouter); //挂载属性 //创建路由对象并配置路由规则 let router = new VueRouter({ //routes routes: [ //一个个对象 { name: 'music', path: '/music', component: Music }, { name: 'movie', path: '/movie', component: Movie } ] }); //new Vue 启动 new Vue({ el: '#app', //让vue知道我们的路由规则 router, //可以简写router render: c => c(App), })
-
package.json和webpack.config.js不变,进入到目录下,进入cmd,执行npm install 安装package.jaon里面的模块产生node_modules目录。然后执行 npm run dev ,页面效果如下:
别忘了main.js里的模块安装
-
编程导航
* 不能保证用户一定会点击某些按钮
* 并且当前操作,除了路由跳转以外,还有一些别的附加操作
* this.$router.go 根据浏览器记录 前进1 后退-1
* this.$router.push(直接跳转到某个页面显示)
- push参数: 字符串 /xxx
- 对象 : `{name:'xxx',query:{id:1},params:{name:2} }` -
复习
* 过滤器,全局,组件内
* 获取DOM元素 ,在元素上ref="xxx"
* 在代码中通过this.$refs.xxx 获取其元素
- 原生DOM标签获取就是原生DOM对象
- 如果是组件标签,获取的就是组件对象 $el继续再获取DOM元素
* 声明周期事件(钩子)回调函数
- created: 数据的初始化、DOM没有生成
- mounted: 将数据装载到DOM元素上,此时有DOM
* 路由
- `window.addEventListener('hashchange',fn);`
- 根据你放`<router-view></router-view><div id="xxx"></div>` 作为一个DOM上的标识
- 最终当锚点值改变触发hashchange的回调函数,我们将指定的模板数据插入到DOM标识上
-
重定向和404
* 进入后,默认就是/
* 重定向 `{ path:'/' ,redirect:'/home' }`
* 重定向 `{ path:'/' ,redirect:{name:'home'} }`
* 404 : 在路由规则的最后的一个规则
- 写一个很强大的匹配
- `{ path:'*' , component:notFoundVue}` -
重定向和404案例
-
目录结构
-
app.vue
<template> <div> <div>头部</div> <!-- 留坑 --> <router-view style="color:red;"></router-view> <div>底部</div> </div> </template> <script> export default { data(){ return { } } } </script> <style> </style>
-
home.vue
<template> <div> 我是首页 </div> </template> <script> export default { data(){ return { } } } </script> <style> </style>
-
index.html
<html> <head> <meta charset="UTF-8"> <title>Document</title> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> </head> <body> <div id="app"></div> </body> </html>
-
main.js
//引入vue import Vue from 'vue'; import VueRouter from 'vue-router'; //引入 import App from './app.vue'; //引入notFoundVue import NotFound from './notFound.vue'; import Home from './home.vue'; //引入home //安装插件 Vue.use(VueRouter); //创建路由对象配置路由规则 let router = new VueRouter(); router.addRoutes([ //重定向 // { path: '/', redirect: '/home' }, // { path: '/home', component: Home } { path: '/', redirect: { name: 'home' } }, { name: 'home', path: '/home', component: Home }, // 最终无法匹配 -> 404 { path: '*', component: NotFound } ]); //构建vue实例 new Vue({ el: '#app', router, render: c => c(App) })
-
notFound.vue
<template> <div> 您要访问的页面出去旅行了。。。 </div> </template> <script> export default { data(){ return { } } } </script> <style> </style>
-
package.json和webpack.config.js不变,进入到目录下,进入cmd,执行npm install 安装package.jaon里面的模块产生node_modules目录。然后执行 npm run dev ,页面效果如下:
直接重定向到home界面,如果不是home,则为:
-
多视图
* 以前可以一次放一个坑对应一个路由和显示一个组件
- 一次行为 = 一个坑 + 一个路由 + 一个组件
- 一次行为 = 多个坑 + 一个路由 + 多个组件
* components 多视图 是一个对象 对象内多个key和value
- key对应视图的name属性
- value 就是要显示的组件对象
* 多个视图`<router-view></router-view>` -> name就是default
* `<router-view name='xxx'></router-view>` -> name就是xxx -
多视图案例
-
目录结构
-
app.vue
<template> <div> <div>我是头部啊</div> <hr/> <!-- 留坑,非常重要 坑名--> <router-view class="b" name="header"></router-view> <router-view class="b" ></router-view> <router-view class="b" name="footer"></router-view> <hr/> <div>我是底部啊</div> </div> </template> <script> export default { data(){ return { } } } </script> <style scoped> .h{ height: 100px; background-color: yellowgreen; } .b{ height: 100px; background-color: skyblue; } .f{ height: 100px; background-color: hotpink; } </style>
-
footer.vue
<template> <div> 底部啊 </div> </template> <script> export default { data(){ return { } } } </script> <style> </style>
-
header.vue
<template> <div> 头部啊 </div> </template> <script> export default { data(){ return { } } } </script> <style> </style>
-
index.html
<html> <head> <meta charset="UTF-8"> <title>Document</title> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> </head> <body> <div id="app"></div> </body> </html>
-
main.js
//引入一堆 import Vue from 'vue'; import VueRouter from 'vue-router'; //主体 import App from './components/app.vue'; //路由切换页面 import header from './components/header.vue' import footer from './components/footer.vue' //注册全局头组件 // Vue.component('headerVue', header); // Vue.component('footerVue', footer); //注册全局底部组件 //安装插件 Vue.use(VueRouter); //挂载属性 //创建路由对象并配置路由规则 let router = new VueRouter({ //routes routes: [{ path: '/', components: { header: footer, default: header, footer: footer } } ] }); //new Vue 启动 new Vue({ el: '#app', //让vue知道我们的路由规则 router, //可以简写router render: c => c(App), })
-
package.json和webpack.config.js不变,进入到目录下,进入cmd,执行npm install 安装package.jaon里面的模块产生node_modules目录。然后执行 npm run dev ,页面效果如下:
-
嵌套路由
* 用单页去实现多页应用,复杂的嵌套路由
* 开发中一般会需要使用
* 视图包含视图
* 路由父子级关系路由期组件内包含着第一层router-view { name:'music' ,path:'/music', component:Music , children:[ 子路由的path /就是绝对路径 不/就是相对父级路径 {name:'music.oumei' ,path:'oumei', component:Oumei }, {name:'music.guochan' ,path:'guochan', component:Guochan } ] }
-
vue-resource(了解)
* 可以安装插件,早期vue团队开发的插件
* 停止维护了,作者推荐使用axios
* options预检请求,是当浏览器发现跨域 + application/json的请求,就会自动发起
* 并且发起的时候携带了一个content-type的头 -
axios
* https://segmentfault.com/a/1190000008470355?utm_source=tuicool&utm_medium=referral
* post请求的时候,如果数据是字符串 默认头就是键值对,否则是对象就是application/json
* this.$axios.get(url,options)
* this.$axios.post(url,data,options)
* options:{ params:{id:1}//查询字符串, headers:{ 'content-type':'xxxxx' },baseURL:'' }
* 全局默认设置 :Axios.defaults.baseURL = 'xxxxx';
* 针对当前这一次请求的相关设置 -
axios案例
-
目录结构
-
app.vue
<template> <div> {{data}} </div> </template> <script> export default { data(){ return { data:[] } },created(){ this.$axios.get('getlunbo',{ params:{ id:'123' }, baseURL:'http://www.baidu.com' }) .then(res=>{ this.data = res.data.message; }) .catch(err=>{ console.log(err); }) // .finally(()=>{ // console.log('最终'); // }) // //post this.$axios.post('postcomment/300', 'content=传智27期,真正霸气的一批' // { // content:'传智27期,再次霸气的一批' // }, // { // //设置 // headers:{ // 'content-type':'application/x-www-form-urlencoded' // } // } ) .then(res=>{ this.data = res.data.message; }) .catch(err=>{ console.log(err); }) } } </script> <style scoped> .h{ height: 100px; background-color: yellowgreen; } .b{ height: 100px; background-color: skyblue; } .f{ height: 100px; background-color: hotpink; } </style>
-
index.html
<html> <head> <meta charset="UTF-8"> <title>Document</title> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> </head> <body> <div id="app"></div> </body> </html>
-
main.js
//引入一堆 import Vue from 'vue'; //主体 import App from './components/app.vue'; //引入 import Axios from 'axios'; Axios.defaults.baseURL = 'http://182.254.146.100:8899/api/'; //给Vue原型挂载一个属性 Vue.prototype.$axios = Axios; //new Vue 启动 new Vue({ el: '#app', render: c => c(App), })
-
package.json和webpack.config.js不变,进入到目录下,进入cmd,执行npm install 安装package.jaon里面的模块产生node_modules目录。然后执行 npm run dev ,页面效果如下:
由于服务器关了,所以没有请求到数据。再三强调,一定要安装main.js里的模块,所以要安装axios。
-
如何练习
* 1:路由核心
- 路由基本使用
- 任选一种路由参数的方式(查询字符串)
- 404(路由匹配规则)
- 嵌套路由
- 编程导航
* 2:http请求
- axios 发起get、post请求 (300)
- 获取 http://182.254.146.100:8899/api/getcomments/300?pageindex=1
- 发起 http://182.254.146.100:8899/api/postcomment/300
- axios挂载属性方式