首先感谢尚硅谷和张天禹老师的教学分享!Respect!
学习来源:B站
https://www.bilibili.com/video/BV1Zy4y1K7SH?p=1&vd_source=07c8a1a7d89af39fe20c3a6894f5ff6a
资料来源:百度网盘
链接:https://pan.baidu.com/s/1Y7mTMXzlBXqKve8KWSPwtg?pwd=7bna
提取码:7bna
文章目录
- 首先感谢尚硅谷和张天禹老师的教学分享!Respect!
- vue_test
- 1. 分析脚手架
- 2. ref属性
- 3.props配置
- 4. mixin(混入)
- 5. 插件
- 6. scoped样式
- 7. 总结TodoList案例
- 8. 浏览器本地存储webStorage
- 9. TodoList_本地存储
- 10. 组件的自定义事件
- 11. TodoList_自定义事件
- 12. 全局事件总线(GlobalEventBus)
- 13. TodoList_事件总线
- 14. 消息订阅与发布(pubsub)
- 15. TodoList_pubsub
- 16. TodoList_nextTick
- 17. Vue封装的过度与动画
- 18. TodoList_动画
- 19. vue脚手架配置代理
- 20. GitHub搜索案例
- 21. GitHub搜索案例_vue-resource
- 22. 插槽
- 23. 求和案例_纯vue版
- Vuex
- 24. 求和案例_vuex版
- 25. 求和案例_getters
- 26. 求和案例_mapState与mapGetters
- 27. 求和案例_mapMutations与mapActions
- 28. 求和案例_多组件共享数据
- 29. 求和案例_vuex模板化编码
- 路由
- 30. 路由的基本使用
- 31. 多级路由
- 32. 路由的query参数
- 33. 命名路由
- 34. 路由的params参数
- 35. 路由的props配置
- 36. `<router-link>`的replace属性
- 37. 编程式路由导航
- 38. 缓存路由组件
- 39. 两个新的生命周期钩子
- 40. 全局路由守卫
- 41. 独享路由守卫
- 42. 组件内路由守卫
- 43. history模式与hash模式
- 44. element-ui组件库
vue_test
1. 分析脚手架
安装脚手架
-
(仅第一次执行)全局安装@vue/cli
npm install -g @vue/cli -
切换到要创建项目的目录,然后使用命令创造项目
vue create 项目名 -
启动项目
npm run serve
脚手架文件结构
├── node_modules
├── public
│ ├── favicon.ico: 页签图标
│ └── index.html: 主页面
├── src
│ ├── assets: 存放静态资源
│ │ └── logo.png
│ │── component: 存放组件
│ │ └── HelloWorld.vue
│ │── App.vue: 汇总所有组件
│ │── main.js: 入口文件
├── .gitignore: git版本管制忽略的配置
├── babel.config.js: babel的配置文件
├── package.json: 应用包配置文件
├── README.md: 应用描述文件
├── package-lock.json:包版本控制文件
关于不同版本的Vue
vue.js与vue.runtime.xxx.js的区别:
- vue.js是完整版的Vue,包含:核心功能 + 模板解析器。
- vue.runtime.xxx.js是运行版的Vue,只包含:核心功能;没有模板解析器。
因为vue.runtime.xxx.js没有模板解析器,所以不能使用template这个配置项,需要使用render函数接收到的createElement函数去指定具体内容。
vue.config.js配置文件
使用vue inspect > output.js可以查看到Vue脚手架的默认配置。
使用vue.config.js可以对脚手架进行个性化定制,详情见:https://cli.vuejs.org/zh
-
components\Student.vue
<template> <div> <h2>学生姓名:{{name}}</h2> <h2>学生年龄:{{age}}</h2> </div> </template> <script> export default { name: 'Student', data() { return { name:'张三', age:18 } } } </script> -
components\School.vue
<template> <div class="demo"> <h2>学校名称:{{name}}</h2> <h2>学校地址:{{address}}</h2> <button @click="showName">点我提示学校名</button> </div> </template> <script> export default { name: 'School', data() { return { name:'尚硅谷', address:'北京' }; }, methods: { showName() { alert(this.name) }, }, }; </script> <style> .demo{ background-color: orange; } </style> -
App.vue
<template> <div> <img src="./assets/logo.png" alt="logo"> <School></School> <Student></Student> </div> </template> <script> // 引入组件 import School from "./components/School" import Student from "./components/Student" export default { name: 'App', components:{ School, Student } }; </script> <style> </style> -
main.js
/* 该文件是整个项目的入口文件 */ // 引入Vue import Vue from 'vue' // 引入App组件,它是所有组件的父组件 import App from './App.vue' // 创建Vue实例对象——vm new Vue({ el:'#app', render: h => h(App) })
2. ref属性
ref属性
- 被用来给元素或子组件注册引用信息(id的替代者)
- 应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)
- 使用方式:
- 打标识:
<h1 ref="xxx">.....</h1>或<School ref="xxx"></School>- 获取:
this.$refs.xxx
-
components\School.vue
<template> <div class="demo"> <h2>学校名称:{{name}}</h2> <h2>学校地址:{{address}}</h2> <button @click="showName">点我提示学校名</button> </div> </template> <script> export default { name: 'School', data() { return { name:'尚硅谷', address:'北京' }; }, methods: { showName() { alert(this.name) }, }, }; </script> <style> .demo{ background-color: orange; } </style> -
App.vue
<template> <div> <h1 v-text="msg" ref="title"></h1> <button ref="btn" @click="showDOM">点我输出上方的DOM元素</button> <School ref="sch" /> </div> </template> <script> // 引入组件 import School from "./components/School" export default { name: 'App', components:{ School }, data(){ return { msg:'欢迎学习vue!' } }, methods:{ showDOM(){ console.log(this.$refs.title); console.log(this.$refs.btn); console.log(this.$refs.sch); } } }; </script> <style> </style> -
控制台输出

3.props配置
props配置项
功能:让组件接收外部传过来的数据
传递数据:
<Demo name="xxx"/>接收数据:
第一种方式(只接收):
props:['name']第二种方式(限制类型):
props:{name:String}第三种方式(限制类型、限制必要性、指定默认值):
props:{ name:{ type:String, //类型 required:true, //必要性 default:'老王' //默认值 } }备注:props是只读的,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求确实需要修改,那么请复制props的内容到data中一份,然后去修改data中的数据。
-
components\Student.vue
<template> <div> <h1>{{msg}}</h1> <h2>学生姓名:{{name}}</h2> <h2>学生性别:{{sex}}</h2> <h2>学生年龄:{{myAge+1}}</h2> <button @click="updateAge">尝试修改收到的年龄</button> </div> </template> <script> export default { name: 'Student', data() { console.log(this); return { msg:'我是一个学Vue的学生', myAge:this.age } }, methods:{ updateAge(){ this.myAge++ } }, // 简单声明接收 // props:['name', 'age', 'sex'] // 接收的同时对数据进行类型限制 // props:{ // name:String, // age:Number, // sex:String // } // 接收的同时对数据进行:类型限制+默认值的指定+必要的限制 props:{ name:{ // name的类型是字符串 type:String, // name是必要的, 如果不提供会警告 required:true }, age:{ type:Number, // 默认值 default:99 }, sex:{ type:String, required:true, } } } </script> -
App.vue
<template> <div> <!-- age如果不加:传输过去的是字符串,运算将变成字符串拼接 --> <Student name="李四" sex="女" :age="18"></Student> </div> </template> <script> // 引入组件 import Student from './components/Student.vue' export default { name: 'App', components:{ Student } }; </script> <style> </style>
4. mixin(混入)
功能:可以把多个组件共用的配置提取成一个混入对象
使用方式:
第一步定义混合:
{ data(){....}, methods:{....} .... }第二步使用混入:
全局混入:
Vue.mixin(xxx)
局部混入:mixins:['xxx']
-
src\mixin.js
export const hunhe = { methods: { showName(){ alert(this.name) } }, mounted() { console.log('你好啊!') }, } export const hunhe2 = { data(){ return { x:100, y:200 } } } -
src\components\Student.vue
<template> <div> <h2 @click="showName">学生姓名:{{name}}</h2> <h2>学生性别:{{sex}}</h2> </div> </template> <script> // 导入mixin.js // import { hunhe, hunhe2 } from '../mixin' export default { name: 'Student', data() { return { name:'张三', sex:'男' } }, // mixins:[hunhe, hunhe2] } </script> -
src\components\School.vue
<template> <div> <h2 @click="showName">学校名称:{{name}}</h2> <h2>学校地址:{{address}}</h2> <!-- <h2>{{x}}</h2> <h2>{{y}}</h2> --> </div> </template> <script> // 引入混合mixin // import { hunhe, hunhe2 } from '../mixin' export default { name: 'School', data() { return { name:'尚硅谷', address:'北京', x:666 }; }, // mixins:[hunhe, hunhe2] }; </script> -
src\App.vue
<template> <div> <School></School> <hr> <Student></Student> </div> </template> <script> // 引入组件 import Student from './components/Student.vue' import School from './components/School.vue' export default { name: 'App', components:{ Student, School } }; </script> <style> </style> -
src\main.js
/* 该文件是整个项目的入口文件 */ // 引入Vue import Vue from 'vue' // 引入App组件,它是所有组件的父组件 import App from './App.vue' // 引入mixin插件 import { hunhe, hunhe2 } from './mixin' // 关闭Vue的生产提示 Vue.config.productionTip = false // 全局加入混合mixin,每一个组件都有 Vue.mixin(hunhe) Vue.mixin(hunhe2) // 创建Vue实例对象——vm new Vue({ el:'#app', render: h => h(App) })
5. 插件
功能:用于增强Vue
本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据。
定义插件:
对象.install = function (Vue, options) { // 1. 添加全局过滤器 Vue.filter(....) // 2. 添加全局指令 Vue.directive(....) // 3. 配置全局混入(合) Vue.mixin(....) // 4. 添加实例方法 Vue.prototype.$myMethod = function () {...} Vue.prototype.$myProperty = xxxx }使用插件:
Vue.use()
-
src\plugins.js
// const plugins = { export default { install(Vue, x, y, z){ console.log(x, y, z) // 全局过滤器 Vue.filter('mySlice', function(value){ return value.slice(0, 4) }) // 定义全局指令 Vue.directive('fbind', { bind(element, binding){ element.value = binding.value }, inserted(element, binding){ element.focus() }, update(element, binding){ element.value = binding.value } }) // 定义混入mixin Vue.mixin({ data(){ return { x:100, y:200 } } }) // 给Vue原型上添加一个方法(vm和vc就都能用了) Vue.prototype.hello = ()=>{ alert('你好啊!') } } } // export default plugins -
src\components\Student.vue
<template> <div> <h2>学生姓名:{{name}}</h2> <h2>学生性别:{{sex}}</h2> </div> </template> <script> export default { name: 'Student', data() { return { name:'张三', sex:'男' } }, } </script> -
src\components\School.vue
<template> <div> <h2>学校名称:{{name | mySlice}}</h2> <h2>学校地址:{{address}}</h2> <button @click="test">点我一下测试hello方法</button> </div> </template> <script> export default { name: 'School', data() { return { name:'尚硅谷', address:'北京', }; }, methods:{ test(){ this.hello() } } }; </script> -
src\App.vue
<template> <div> <School></School> <hr> <Student></Student> </div> </template> <script> // 引入组件 import Student from './components/Student.vue' import School from './components/School.vue' export default { name: 'App', components:{ Student, School } }; </script> <style> </style> -
src\main.js
/* 该文件是整个项目的入口文件 */ // 引入Vue import Vue from 'vue' // 引入App组件,它是所有组件的父组件 import App from './App.vue' // 引入插件 import plugins from './plugins' // 关闭Vue的生产提示 Vue.config.productionTip = false // 应用插件 Vue.use(plugins, 1, 2, 3) // 创建Vue实例对象——vm new Vue({ el:'#app', render: h => h(App) })
6. scoped样式
- 作用:让样式在局部生效,防止冲突。
- 写法:
<style scoped>注:使用
<style lang="less" scoped></style>需要根据webpack版本安装less-loader我的webpack版本为5.7.*,安装的less-loader版本为6
npm install less-loader@6
-
src\components\Student.vue
<template> <div class="demo"> <h2 class="title">学生姓名:{{name}}</h2> <h2 class="atguigu">学生性别:{{sex}}</h2> </div> </template> <script> export default { name: 'Student', data() { return { name:'张三', sex:'男' } }, } </script> <style lang="less" scoped> .demo{ background-color: pink; .atguigu{ font-size: 40px; } } </style> -
src\components\School.vue
<template> <div class="demo"> <h2 class="title">学校名称:{{name}}</h2> <h2>学校地址:{{address}}</h2> </div> </template> <script> export default { name: 'School', data() { return { name:'尚硅谷', address:'北京', }; } }; </script> <style scoped> .demo{ background-color: skyblue; } </style> -
src\App.vue
<template> <div> <h1 class="title">你好啊!</h1> <School></School> <Student></Student> </div> </template> <script> // 引入组件 import Student from './components/Student.vue' import School from './components/School.vue' export default { name: 'App', components:{ Student, School } }; </script> <style> .title{ color: red; } </style>
7. 总结TodoList案例
组件化编码流程:
(1).拆分静态组件:组件要按照功能点拆分,命名不要与html元素冲突。
(2).实现动态组件:考虑好数据的存放位置,数据是一个组件在用,还是一些组件在用:
1).一个组件在用:放在组件自身即可。 2). 一些组件在用:放在他们共同的父组件上(<span style="color:red">状态提升</span>)。(3).实现交互:从绑定事件开始。
props适用于:
(1).父组件 ==> 子组件 通信
(2).子组件 ==> 父组件 通信(要求父先给子一个函数)
使用v-model时要切记:v-model绑定的值不能是props传过来的值,因为props是不可以修改的!
props传过来的若是对象类型的值,修改对象中的属性时Vue不会报错,但不推荐这样做。
-
src\App.vue
<template> <div id="root"> <div class="todo-container"> <div class="todo-wrap"> <Header :addTodo="addTodos"></Header> <List :todos="todos" :checkTodo="checkTodo" :deleteTodo="deleteTodo"></List> <Footer :todos="todos" :checkAllTodo="checkAllTodo" :clearAllTodo="clearAllTodo"></Footer> </div> </div> </div> </template> <script> // 引入组件 import Header from './components/Header' import Footer from './components/Footer' import List from './components/List' export default { name: 'App', components:{ Header, Footer, List }, data(){ return { // 由于todos是Header组件和Footer组件都在使用,所以放在App中(状态提升) todos:[ {id:'001', title:'抽烟', done:false}, {id:'002', title:'喝酒', done:false}, {id:'003', title:'烫头', done:true}, ] } }, methods: { // 添加一个todo addTodos(todoObj) { this.todos.unshift(todoObj) }, // 勾选or取消勾选一个todo checkTodo(id){ this.todos.forEach((todo)=>{ if (todo.id === id) { todo.done = !todo.done } }) }, // 删除一个todo deleteTodo(id){ this.todos = this.todos.filter((todo)=>{ return todo.id !== id }) }, // 全选or取消全选 checkAllTodo(done){ this.todos.forEach((todo)=>{ todo.done = done }) }, // 清除所有已经完成的todo clearAllTodo(){ this.todos = this.todos.filter((todo)=>{ return !todo.done }) } }, }; </script> <style> /*base*/ body { background: #fff; } .btn { display: inline-block; padding: 4px 12px; margin-bottom: 0; font-size: 14px; line-height: 20px; text-align: center; vertical-align: middle; cursor: pointer; box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); border-radius: 4px; } .btn-danger { color: #fff; background-color: #da4f49; border: 1px solid #bd362f; } .btn-danger:hover { color: #fff; background-color: #bd362f; } .btn:focus { outline: none; } .todo-container { width: 600px; margin: 0 auto; } .todo-container .todo-wrap { padding: 10px; border: 1px solid #ddd; border-radius: 5px; } </style> -
src\components\Header.vue
<template> <div class="todo-header"> <input type="text" placeholder="请输入你的任务名称,按回车键确认" v-model="title" @keyup.enter="add" /> </div> </template> <script> // NanoID 是软件开发中最常用的通用标识符之一 import { nanoid } from "nanoid"; export default { name: 'Header', props:['addTodo'], data(){ return { // 收集用户输入的title title:'' } }, methods:{ add(){ // 校验数据 if (!this.title.trim()) { return alert('输入不能为空!') } // 将用户的输入包装成一个todo对象 const todoObj = { id:nanoid(), title:this.title, done:false } // 通过App组件去添加一个todo对象 this.addTodo(todoObj) // 清空输入 this.title = '' } } }; </script> <style lang="css" scoped> /*header*/ .todo-header input { width: 560px; height: 28px; font-size: 14px; border: 1px solid #ccc; border-radius: 4px; padding: 4px 7px; } .todo-header input:focus { outline: none; border-color: rgba(82, 168, 236, 0.8); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); } </style> -
src\components\Footer.vue
<template> <div class="todo-footer"> <label> <!-- <input type="checkbox" :checked="isAll" @change="checkAll"/> --> <input type="checkbox" v-model="isAll"> </label> <span> <span>已完成{{doneTotal}}</span> / 全部{{total}} </span> <button class="btn btn-danger" @click="clearAll">清除已完成任务</button> </div> </template> <script> export default { name: 'Footer', props:['todos', 'checkAllTodo', 'clearAllTodo'], computed:{ // 总数 total(){ return this.todos.length }, doneTotal(){ // 此处使用reduce方法做条件统计 /* reducer 逐个遍历数组元素, 每一步都将当前元素的值与上一步的计算结果相加 (上一步的计算结果是当前元素之前所有元素的总和) ——直到没有更多的元素被相加。 */ // const x = this.todos.reduce((pre, current)=>{ // // console.log('@', pre, current); // return pre + (current.done ? 1 : 0) // }, 0) // return x // 简写 return this.todos.reduce((pre, current)=> pre + (current.done ? 1 : 0), 0) }, // 控制全选框 isAll:{ // 全选框是否勾选 get(){ return this.doneTotal === this.total && this.total > 0 }, // isAll被修改时set被调用 set(value){ this.checkAllTodo(value) } } }, methods:{ // checkAll(event){ // // console.log(event.target); // this.checkAllTodo(event.target.checked) // }, // 清空所有已完成 clearAll(){ this.clearAllTodo() } } }; </script> <style lang="css" scoped> /*footer*/ .todo-footer { height: 40px; line-height: 40px; padding-left: 6px; margin-top: 5px; } .todo-footer label { display: inline-block; margin-right: 20px; cursor: pointer; } .todo-footer label input { position: relative; top: -1px; vertical-align: middle; margin-right: 5px; } .todo-footer button { float: right; margin-top: 5px; } </style> -
src\components\List.vue
<template> <ul class="todo-main"> <Item v-for="todoObj in todos" :key="todoObj.id" :todo="todoObj" :checkTodo="checkTodo" :deleteTodo="deleteTodo" ></Item> </ul> </template> <script> // 引入Item import Item from './Item' export default { name: 'List', components:{ Item }, // 声明接收App传递过来的数据,其中todos是自己用的,checkTodo和deleteTodo是给自组建Item用的 props:['todos', 'checkTodo', 'deleteTodo'] }; </script> <style lang="css" scoped> /*main*/ .todo-main { margin-left: 0px; border: 1px solid #ddd; border-radius: 2px; padding: 0px; } .todo-empty { height: 40px; line-height: 40px; border: 1px solid #ddd; border-radius: 2px; padding-left: 5px; margin-top: 10px; } </style> -
src\components\Item.vue
<template> <li> <label> <!-- 如下代码也能实现功能,但是不推荐,因为违反规则,修改了props --> <!-- <input type="checkbox" v-model="todo.done"> --> <input type="checkbox" :checked="todo.done" @change="handleCheck(todo.id)"/> <span>{{todo.title}}</span> </label> <button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button> </li> </template> <script> export default { name: 'Item', // 声明接收todo、checkTodo、deleteTodo props:['todo', 'checkTodo', 'deleteTodo'], methods:{ // 勾选or取消勾选 handleCheck(id){ // 通知App组件将对应的todo对象的done值取反 this.checkTodo(id) }, // 删除 handleDelete(id){ if (confirm('确定删除吗?')) { // 通知App组件将对应的todo对象删除 this.deleteTodo(id) } } } }; </script> <style lang="css" scoped> /*item*/ li { list-style: none; height: 36px; line-height: 36px; padding: 0 5px; border-bottom: 1px solid #ddd; } li label { float: left; cursor: pointer; } li label li input { vertical-align: middle; margin-right: 6px; position: relative; top: -1px; } li button { float: right; /* display: none; */ margin-top: 3px; } li:before { content: initial; } li:last-child { border-bottom: none; } </style>
8. 浏览器本地存储webStorage
存储内容大小一般支持5MB左右(不同浏览器可能还不一样)
浏览器端通过 Window.sessionStorage 和 Window.localStorage 属性来实现本地存储机制。
相关API:
xxxxxStorage.setItem('key', 'value');
该方法接受一个键和值作为参数,会把键值对添加到存储中,如果键名存在,则更新其对应的值。
xxxxxStorage.getItem('person');该方法接受一个键名作为参数,返回键名对应的值。
xxxxxStorage.removeItem('key');该方法接受一个键名作为参数,并把该键名从存储中删除。
xxxxxStorage.clear()该方法会清空存储中的所有数据。备注:
- SessionStorage存储的内容会随着浏览器窗口关闭而消失。
- LocalStorage存储的内容,需要手动清除才会消失。
xxxxxStorage.getItem(xxx)如果xxx对应的value获取不到,那么getItem的返回值是null。JSON.parse(null)的结果依然是null。
-
08_浏览器本地存储webStorage\sessionStorage.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>sessionStorage</title> </head> <body> <h2>sessionStorage</h2> <button onclick="saveData()">点我保存一个数据</button> <button onclick="readData()">点我读取一个数据</button> <button onclick="deleteData()">点我删除一个数据</button> <button onclick="deleteAllData()">点我清空数据</button> <script type="text/javascript"> let p = {name:'张三', age:18} function saveData(){ sessionStorage.setItem('msg', 'hello!!!!') sessionStorage.setItem('msg2', 666) sessionStorage.setItem('person', JSON.stringify(p)) } function readData(){ console.log(sessionStorage.getItem('msg')); console.log(sessionStorage.getItem('msg2')); const result = sessionStorage.getItem('person') console.log(JSON.parse(result)); } function deleteData(){ sessionStorage.removeItem('msg2') } function deleteAllData(){ sessionStorage.clear() } </script> </body> </html> -
08_浏览器本地存储webStorage\localStorage.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>localStorage</title> </head> <body> <h2>sessionStorage</h2> <button onclick="saveData()">点我保存一个数据</button> <button onclick="readData()">点我读取一个数据</button> <button onclick="deleteData()">点我删除一个数据</button> <button onclick="deleteAllData()">点我清空数据</button> <script type="text/javascript"> let p = {name:'张三', age:18} function saveData(){ localStorage.setItem('msg', 'hello!!!!') localStorage.setItem('msg2', 666) localStorage.setItem('person', JSON.stringify(p)) } function readData(){ console.log(localStorage.getItem('msg')); console.log(localStorage.getItem('msg2')); const result = localStorage.getItem('person') console.log(JSON.parse(result)); } function deleteData(){ localStorage.removeItem('msg2') } function deleteAllData(){ localStorage.clear() } </script> </body> </html>
9. TodoList_本地存储
-
src\App.vue
<template> <div id="root"> <div class="todo-container"> <div class="todo-wrap"> <Header :addTodo="addTodos"></Header> <List :todos="todos" :checkTodo="checkTodo" :deleteTodo="deleteTodo"></List> <Footer :todos="todos" :checkAllTodo="checkAllTodo" :clearAllTodo="clearAllTodo"></Footer> </div> </div> </div> </template> <script> // 引入组件 import Header from './components/Header' import Footer from './components/Footer' import List from './components/List' export default { name: 'App', components:{ Header, Footer, List }, data(){ return { // 由于todos是Header组件和Footer组件都在使用,所以放在App中(状态提升) // todos:[ // {id:'001', title:'抽烟', done:false}, // {id:'002', title:'喝酒', done:false}, // {id:'003', title:'烫头', done:true}, // ] // 从浏览器本地存储中获取todos todos:JSON.parse(localStorage.getItem('todos')) || [] } }, methods: { // 添加一个todo addTodos(todoObj) { this.todos.unshift(todoObj) }, // 勾选or取消勾选一个todo checkTodo(id){ this.todos.forEach((todo)=>{ if (todo.id === id) { todo.done = !todo.done } }) }, // 删除一个todo deleteTodo(id){ this.todos = this.todos.filter((todo)=>{ return todo.id !== id }) }, // 全选or取消全选 checkAllTodo(done){ this.todos.forEach((todo)=>{ todo.done = done }) }, // 清除所有已经完成的todo clearAllTodo(){ this.todos = this.todos.filter((todo)=>{ return !todo.done }) } }, // 通过监视属性将todos存入浏览器本地存储 watch:{ todos:{ deep:true, handler(value){ localStorage.setItem('todos', JSON.stringify(value)) } } } }; </script> <style> /*base*/ body { background: #fff; } .btn { display: inline-block; padding: 4px 12px; margin-bottom: 0; font-size: 14px; line-height: 20px; text-align: center; vertical-align: middle; cursor: pointer; box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); border-radius: 4px; } .btn-danger { color: #fff; background-color: #da4f49; border: 1px solid #bd362f; } .btn-danger:hover { color: #fff; background-color: #bd362f; } .btn:focus { outline: none; } .todo-container { width: 600px; margin: 0 auto; } .todo-container .todo-wrap { padding: 10px; border: 1px solid #ddd; border-radius: 5px; } </style> -
测试结果

10. 组件的自定义事件
一种组件间通信的方式,适用于:子组件 ===> 父组件
使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)。
绑定自定义事件:
第一种方式,在父组件中:
<Demo @atguigu="test"/>或<Demo v-on:atguigu="test"/>第二种方式,在父组件中:
<Demo ref="demo"/> ...... mounted(){ this.$refs.xxx.$on('atguigu',this.test) }若想让自定义事件只能触发一次,可以使用
once修饰符,或$once方法。触发自定义事件:
this.$emit('atguigu',数据)解绑自定义事件
this.$off('atguigu')组件上也可以绑定原生DOM事件,需要使用
native修饰符。注意:通过
this.$refs.xxx.$on('atguigu',回调)绑定自定义事件时,回调要么配置在methods中,要么用箭头函数,否则this指向会出问题!
-
src\App.vue
<template> <div id="root"> <h1>{{msg}},学生的姓名是{{studentName}}</h1> <!-- 通过父组件给子组件传递函数类型的props实现:子给父传递数据 --> <School :getSchoolName="getSchoolName"/> <!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法,使用@或者v-on) --> <Student @atguigu="getStudentName" @demo="m1"/> <!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法,使用ref) --> <!-- <Student ref="student" @click="show"/> --> <Student ref="student" @click.native="show"/> </div> </template> <script> // 引入组件 import School from './components/School' import Student from './components/Student' export default { name: 'App', components:{ School, Student }, data(){ return { msg:'你好啊', studentName:'' } }, methods: { getSchoolName(name){ console.log('App收到了学校名', name); }, getStudentName(name, ...params){ console.log('App收到了学生名', name, params); this.studentName = name }, m1(){ console.log('demo事件被触发了'); }, show(){ alert(123) } }, mounted(){ // 绑定自定义事件 // this.$refs.student.$on('atguigu', this.getStudentName) // 绑定自定义事件(一次性) this.$refs.student.$once('atguigu', this.getStudentName) } }; </script> <style> .app{ background-color: gray; padding: 5px; } </style> -
src\components\School.vue
<template> <div class="school"> <h2>学校名称:{{name}}</h2> <h2>学校地址:{{address}}</h2> <button @click="sendSchoolName">把学校名给App</button> </div> </template> <script> export default { name: 'School', props:['getSchoolName'], data() { return { name:'尚硅谷', address:'北京', }; }, methods:{ sendSchoolName(){ this.getSchoolName(this.name) } } }; </script> <style scoped> .school{ background-color: skyblue; padding: 5px; } </style> -
src\components\Student.vue
<template> <div class="student"> <h2>学生姓名:{{name}}</h2> <h2>学生性别:{{sex}}</h2> <h2>当前求和为:{{number}}</h2> <button @click="add">点我number++</button> <button @click="sendStudentName">把学生名给App</button> <button @click="unbind">解绑atguigu事件</button> <button @click="death">销毁当前Student组件的实例(vc)</button> </div> </template> <script> export default { name: 'Student', data() { return { name:'张三', sex:'男', number:0 } }, methods:{ add(){ console.log('add回调被调用了'); this.number++ }, sendStudentName(){ // 触发Student组件实例上的atguigu事件 this.$emit('atguigu', this.name, 666, 888, 999) this.$emit('demo') this.$emit('click') }, unbind(){ // 解绑一个自定义事件 this.$off('atguigu') // 解绑多个自定义事件 this.$off(['atguigu', 'demo']) // 解绑所有自定义事件 this.$off() }, death(){ // 摧毁当前Student组件的实例,销毁后所有的Student实例的自定义事件全都不奏效 this.$destroy() } } } </script> <style lang="less" scoped> .student{ background-color: pink; padding: 5px; margin-top: 30px; } </style>
11. TodoList_自定义事件
-
src\App.vue
<template> <div id="root"> <div class="todo-container"> <div class="todo-wrap"> <!-- <Header :addTodo="addTodos"></Header> --> <Header @addTodo="addTodos"></Header> <List :todos="todos" :checkTodo="checkTodo" :deleteTodo="deleteTodo"></List> <!-- <Footer :todos="todos" :checkAllTodo="checkAllTodo" :clearAllTodo="clearAllTodo"></Footer> --> <Footer :todos="todos" @checkAllTodo="checkAllTodo" @clearAllTodo="clearAllTodo"></Footer> </div> </div> </div> </template> <script> // 引入组件 import Header from './components/Header' import Footer from './components/Footer' import List from './components/List' export default { name: 'App', components:{ Header, Footer, List }, data(){ return { // 由于todos是Header组件和Footer组件都在使用,所以放在App中(状态提升) // todos:[ // {id:'001', title:'抽烟', done:false}, // {id:'002', title:'喝酒', done:false}, // {id:'003', title:'烫头', done:true}, // ] // 从浏览器本地存储中获取todos todos:JSON.parse(localStorage.getItem('todos')) || [] } }, methods: { // 添加一个todo addTodos(todoObj) { this.todos.unshift(todoObj) }, // 勾选or取消勾选一个todo checkTodo(id){ this.todos.forEach((todo)=>{ if (todo.id === id) { todo.done = !todo.done } }) }, // 删除一个todo deleteTodo(id){ this.todos = this.todos.filter((todo)=>{ return todo.id !== id }) }, // 全选or取消全选 checkAllTodo(done){ this.todos.forEach((todo)=>{ todo.done = done }) }, // 清除所有已经完成的todo clearAllTodo(){ this.todos = this.todos.filter((todo)=>{ return !todo.done }) } }, // 通过监视属性将todos存入浏览器本地存储 watch:{ todos:{ deep:true, handler(value){ localStorage.setItem('todos', JSON.stringify(value)) } } }, }; </script> <style> /*base*/ body { background: #fff; } .btn { display: inline-block; padding: 4px 12px; margin-bottom: 0; font-size: 14px; line-height: 20px; text-align: center; vertical-align: middle; cursor: pointer; box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); border-radius: 4px; } .btn-danger { color: #fff; background-color: #da4f49; border: 1px solid #bd362f; } .btn-danger:hover { color: #fff; background-color: #bd362f; } .btn:focus { outline: none; } .todo-container { width: 600px; margin: 0 auto; } .todo-container .todo-wrap { padding: 10px; border: 1px solid #ddd; border-radius: 5px; } </style> -
src\components\Header.vue
<template> <div class="todo-header"> <input type="text" placeholder="请输入你的任务名称,按回车键确认" v-model="title" @keyup.enter="add" /> </div> </template> <script> // NanoID 是软件开发中最常用的通用标识符之一 import { nanoid } from "nanoid"; export default { name: 'Header', // props:['addTodo'], data(){ return { // 收集用户输入的title title:'' } }, methods:{ add(){ // 校验数据 if (!this.title.trim()) { return alert('输入不能为空!') } // 将用户的输入包装成一个todo对象 const todoObj = { id:nanoid(), title:this.title, done:false } // // 通过App组件去添加一个todo对象 // this.addTodo(todoObj) // 通过触发addTodo事件来传递todoObj this.$emit('addTodo', todoObj) // 清空输入 this.title = '' } } }; </script> <style lang="css" scoped> /*header*/ .todo-header input { width: 560px; height: 28px; font-size: 14px; border: 1px solid #ccc; border-radius: 4px; padding: 4px 7px; } .todo-header input:focus { outline: none; border-color: rgba(82, 168, 236, 0.8); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); } </style> -
src\components\Footer.vue
<template> <div class="todo-footer"> <label> <!-- <input type="checkbox" :checked="isAll" @change="checkAll"/> --> <input type="checkbox" v-model="isAll"> </label> <span> <span>已完成{{doneTotal}}</span> / 全部{{total}} </span> <button class="btn btn-danger" @click="clearAll">清除已完成任务</button> </div> </template> <script> export default { name: 'Footer', // props:['todos', 'checkAllTodo', 'clearAllTodo'], props:['todos'], computed:{ // 总数 total(){ return this.todos.length }, doneTotal(){ // 此处使用reduce方法做条件统计 /* reducer 逐个遍历数组元素, 每一步都将当前元素的值与上一步的计算结果相加 (上一步的计算结果是当前元素之前所有元素的总和) ——直到没有更多的元素被相加。 */ // const x = this.todos.reduce((pre, current)=>{ // // console.log('@', pre, current); // return pre + (current.done ? 1 : 0) // }, 0) // return x // 简写 return this.todos.reduce((pre, current)=> pre + (current.done ? 1 : 0), 0) }, // 控制全选框 isAll:{ // 全选框是否勾选 get(){ return this.doneTotal === this.total && this.total > 0 }, // isAll被修改时set被调用 set(value){ // this.checkAllTodo(value) // 通过checkAllTodo事件触发 this.$emit('checkAllTodo', value) } } }, methods:{ // checkAll(event){ // // console.log(event.target); // this.checkAllTodo(event.target.checked) // }, // 清空所有已完成 clearAll(){ // this.clearAllTodo() // 通过clearAllTodo事件触发 this.$emit('clearAllTodo') } } }; </script> <style lang="css" scoped> /*footer*/ .todo-footer { height: 40px; line-height: 40px; padding-left: 6px; margin-top: 5px; } .todo-footer label { display: inline-block; margin-right: 20px; cursor: pointer; } .todo-footer label input { position: relative; top: -1px; vertical-align: middle; margin-right: 5px; } .todo-footer button { float: right; margin-top: 5px; } </style>
12. 全局事件总线(GlobalEventBus)
一种组件间通信的方式,适用于任意组件间通信。
安装全局事件总线:
new Vue({ ...... beforeCreate() { Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm }, ...... })使用事件总线:
接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身。
methods(){ demo(data){......} } ...... mounted() { this.$bus.$on('xxxx',this.demo) }提供数据:
this.$bus.$emit('xxxx',数据)最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件。
-
src\main.js
/* 该文件是整个项目的入口文件 */ // 引入Vue import Vue from 'vue' // 引入App组件,它是所有组件的父组件 import App from './App.vue' // 关闭Vue的生产提示 Vue.config.productionTip = false // 创建Vue实例对象——vm new Vue({ el:'#app', render: h => h(App), beforeCreate(){ // 测试在Vue原型上绑定数据,组件能否读取 // Vue.prototype.x = 88 // 安装全局事件总线 Vue.prototype.$bus = this } }) -
src\App.vue
<template> <div id="root"> <h1>{{msg}}</h1> <School /> <Student /> </div> </template> <script> // 引入组件 import School from './components/School' import Student from './components/Student' export default { name: 'App', components:{ School, Student }, data(){ return { msg:'你好啊', } }, }; </script> <style> .app{ background-color: gray; padding: 5px; } </style> -
src\components\School.vue
<template> <div class="school"> <h2>学校名称:{{name}}</h2> <h2>学校地址:{{address}}</h2> </div> </template> <script> export default { name: 'School', props:['getSchoolName'], data() { return { name:'尚硅谷', address:'北京', }; }, mounted(){ // console.log('School', this); this.$bus.$on('hello', (data)=>{ console.log('我是School组件,我收到了数据',data) }) }, beforeDestroy(){ this.$bus.$off('hello') } }; </script> <style scoped> .school{ background-color: skyblue; padding: 5px; } </style> -
src\components\Student.vue
<template> <div class="student"> <h2>学生姓名:{{name}}</h2> <h2>学生性别:{{sex}}</h2> <button @click="sendStudentName">把学生名给School组件</button> </div> </template> <script> export default { name: 'Student', data() { return { name:'张三', sex:'男', } }, methods:{ sendStudentName(){ this.$bus.$emit('hello', this.name) } }, mounted(){ // 测试在Vue原型上绑定数据,组件能否读取 // 可以 // console.log('Student', this.x); } } </script> <style lang="less" scoped> .student{ background-color: pink; padding: 5px; margin-top: 30px; } </style>
13. TodoList_事件总线
-
src\App.vue
<template> <div id="root"> <div class="todo-container"> <div class="todo-wrap"> <!-- <Header :addTodo="addTodos"></Header> --> <Header @addTodo="addTodos"></Header> <!-- <List :todos="todos" :checkTodo="checkTodo" :deleteTodo="deleteTodo"></List> --> <List :todos="todos"></List> <!-- <Footer :todos="todos" :checkAllTodo="checkAllTodo" :clearAllTodo="clearAllTodo"></Footer> --> <Footer :todos="todos" @checkAllTodo="checkAllTodo" @clearAllTodo="clearAllTodo"></Footer> </div> </div> </div> </template> <script> // 引入组件 import Header from './components/Header' import Footer from './components/Footer' import List from './components/List' export default { name: 'App', components:{ Header, Footer, List }, data(){ return { // 由于todos是Header组件和Footer组件都在使用,所以放在App中(状态提升) // todos:[ // {id:'001', title:'抽烟', done:false}, // {id:'002', title:'喝酒', done:false}, // {id:'003', title:'烫头', done:true}, // ] // 从浏览器本地存储中获取todos todos:JSON.parse(localStorage.getItem('todos')) || [] } }, methods: { // 添加一个todo addTodos(todoObj) { this.todos.unshift(todoObj) }, // 勾选or取消勾选一个todo checkTodo(id){ this.todos.forEach((todo)=>{ if (todo.id === id) { todo.done = !todo.done } }) }, // 删除一个todo deleteTodo(id){ this.todos = this.todos.filter((todo)=>{ return todo.id !== id }) }, // 全选or取消全选 checkAllTodo(done){ this.todos.forEach((todo)=>{ todo.done = done }) }, // 清除所有已经完成的todo clearAllTodo(){ this.todos = this.todos.filter((todo)=>{ return !todo.done }) } }, // 通过监视属性将todos存入浏览器本地存储 watch:{ todos:{ deep:true, handler(value){ localStorage.setItem('todos', JSON.stringify(value)) } } }, mounted(){ // 绑定全局事件 this.$bus.$on('checkTodo', this.checkTodo) this.$bus.$on('deleteTodo', this.deleteTodo) }, beforeDestroy(){ // 解绑全局事件 this.$bus.$off('checkTodo') this.$bus.$off('deleteTodo') }, }; </script> <style> /*base*/ body { background: #fff; } .btn { display: inline-block; padding: 4px 12px; margin-bottom: 0; font-size: 14px; line-height: 20px; text-align: center; vertical-align: middle; cursor: pointer; box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); border-radius: 4px; } .btn-danger { color: #fff; background-color: #da4f49; border: 1px solid #bd362f; } .btn-danger:hover { color: #fff; background-color: #bd362f; } .btn:focus { outline: none; } .todo-container { width: 600px; margin: 0 auto; } .todo-container .todo-wrap { padding: 10px; border: 1px solid #ddd; border-radius: 5px; } </style> -
src\components\List.vue
<template> <ul class="todo-main"> <!-- <Item v-for="todoObj in todos" :key="todoObj.id" :todo="todoObj" :checkTodo="checkTodo" :deleteTodo="deleteTodo" /> --> <!-- 使用全局事件总线就不需要再进行参数传递 --> <Item v-for="todoObj in todos" :key="todoObj.id" :todo="todoObj" /> </ul> </template> <script> // 引入Item import Item from './Item' export default { name: 'List', components:{ Item }, // 声明接收App传递过来的数据,其中todos是自己用的,checkTodo和deleteTodo是给自组建Item用的 // props:['todos', 'checkTodo', 'deleteTodo'] // 用全局事件总线就不需要再进行参数传递 props:['todos'] }; </script> <style lang="css" scoped> /*main*/ .todo-main { margin-left: 0px; border: 1px solid #ddd; border-radius: 2px; padding: 0px; } .todo-empty { height: 40px; line-height: 40px; border: 1px solid #ddd; border-radius: 2px; padding-left: 5px; margin-top: 10px; } </style> -
src\components\Item.vue
<template> <li> <label> <!-- 如下代码也能实现功能,但是不推荐,因为违反规则,修改了props --> <!-- <input type="checkbox" v-model="todo.done"> --> <input type="checkbox" :checked="todo.done" @change="handleCheck(todo.id)"/> <span>{{todo.title}}</span> </label> <button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button> </li> </template> <script> export default { name: 'Item', // 声明接收todo、checkTodo、deleteTodo // props:['todo', 'checkTodo', 'deleteTodo'], props:['todo'], methods:{ // 勾选or取消勾选 handleCheck(id){ // 通知App组件将对应的todo对象的done值取反 // this.checkTodo(id) // 使用全局事件总线 this.$bus.$emit('checkTodo', id) }, // 删除 handleDelete(id){ if (confirm('确定删除吗?')) { // 通知App组件将对应的todo对象删除 // this.deleteTodo(id) // 使用全局事件总线 this.$bus.$emit('deleteTodo', id) } } } }; </script> <style lang="css" scoped> /*item*/ li { list-style: none; height: 36px; line-height: 36px; padding: 0 5px; border-bottom: 1px solid #ddd; } li label { float: left; cursor: pointer; } li label li input { vertical-align: middle; margin-right: 6px; position: relative; top: -1px; } li button { float: right; /* display: none; */ margin-top: 3px; } li:before { content: initial; } li:last-child { border-bottom: none; } </style>
14. 消息订阅与发布(pubsub)
一种组件间通信的方式,适用于任意组件间通信。
使用步骤:
安装pubsub:
npm i pubsub-js引入:
import pubsub from 'pubsub-js'接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身。
methods(){ demo(data){......} } ...... mounted() { this.pid = pubsub.subscribe('xxx',this.demo) //订阅消息 }提供数据:
pubsub.publish('xxx',数据)最好在beforeDestroy钩子中,用
PubSub.unsubscribe(pid)去取消订阅。
-
src\components\Student.vue
<template> <div class="student"> <h2>学生姓名:{{name}}</h2> <h2>学生性别:{{sex}}</h2> <button @click="sendStudentName">把学生名给School组件</button> </div> </template> <script> // 引入pubsub-js import pubsub from 'pubsub-js' export default { name: 'Student', data() { return { name:'张三', sex:'男', } }, methods:{ sendStudentName(){ // this.$bus.$emit('hello', this.name) // 使用pubsub发布hello消息 pubsub.publish('hello', this.name) } }, } </script> <style lang="less" scoped> .student{ background-color: pink; padding: 5px; margin-top: 30px; } </style> -
src\components\School.vue
<template> <div class="school"> <h2>学校名称:{{name}}</h2> <h2>学校地址:{{address}}</h2> </div> </template> <script> // 引入pubsub-js import pubsub from 'pubsub-js' export default { name: 'School', props:['getSchoolName'], data() { return { name:'尚硅谷', address:'北京', }; }, mounted(){ // console.log('School', this); // this.$bus.$on('hello', (data)=>{ // console.log('我是School组件,我收到了数据',data) // }) // 使用pubsub订阅消息 this.pubId = pubsub.subscribe('hello', (msgName, data)=>{ console.log(this) console.log('有人发布了hello消息,hello消息的回调执行了', msgName, data) }) }, beforeDestroy(){ // this.$bus.$off('hello') // 销毁时取消订阅 pubsub.unsubscribe(this.pubId) } }; </script> <style scoped> .school{ background-color: skyblue; padding: 5px; } </style>
15. TodoList_pubsub
-
src\components\Item.vue
<template> <li> <label> <!-- 如下代码也能实现功能,但是不推荐,因为违反规则,修改了props --> <!-- <input type="checkbox" v-model="todo.done"> --> <input type="checkbox" :checked="todo.done" @change="handleCheck(todo.id)"/> <span>{{todo.title}}</span> </label> <button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button> </li> </template> <script> // 引入pubsub import pubsub from 'pubsub-js' export default { name: 'Item', // 声明接收todo、checkTodo、deleteTodo // props:['todo', 'checkTodo', 'deleteTodo'], props:['todo'], methods:{ // 勾选or取消勾选 handleCheck(id){ // 通知App组件将对应的todo对象的done值取反 // this.checkTodo(id) // 使用全局事件总线 this.$bus.$emit('checkTodo', id) }, // 删除 handleDelete(id){ if (confirm('确定删除吗?')) { // 通知App组件将对应的todo对象删除 // this.deleteTodo(id) // 使用全局事件总线 // this.$bus.$emit('deleteTodo', id) // 使用pubsub发布deleteTodo消息 pubsub.publish('deleteTodo', id) } } } }; </script> <style lang="css" scoped> /*item*/ li { list-style: none; height: 36px; line-height: 36px; padding: 0 5px; border-bottom: 1px solid #ddd; } li label { float: left; cursor: pointer; } li label li input { vertical-align: middle; margin-right: 6px; position: relative; top: -1px; } li button { float: right; /* display: none; */ margin-top: 3px; } li:before { content: initial; } li:last-child { border-bottom: none; } </style> -
src\App.vue
<template> <div id="root"> <div class="todo-container"> <div class="todo-wrap"> <!-- <Header :addTodo="addTodos"></Header> --> <Header @addTodo="addTodos"></Header> <!-- <List :todos="todos" :checkTodo="checkTodo" :deleteTodo="deleteTodo"></List> --> <List :todos="todos"></List> <!-- <Footer :todos="todos" :checkAllTodo="checkAllTodo" :clearAllTodo="clearAllTodo"></Footer> --> <Footer :todos="todos" @checkAllTodo="checkAllTodo" @clearAllTodo="clearAllTodo"></Footer> </div> </div> </div> </template> <script> // 引入组件 import Header from './components/Header' import Footer from './components/Footer' import List from './components/List' // 引入pubsub import pubsub from 'pubsub-js' export default { name: 'App', components:{ Header, Footer, List }, data(){ return { // 由于todos是Header组件和Footer组件都在使用,所以放在App中(状态提升) // todos:[ // {id:'001', title:'抽烟', done:false}, // {id:'002', title:'喝酒', done:false}, // {id:'003', title:'烫头', done:true}, // ] // 从浏览器本地存储中获取todos todos:JSON.parse(localStorage.getItem('todos')) || [] } }, methods: { // 添加一个todo addTodos(todoObj) { this.todos.unshift(todoObj) }, // 勾选or取消勾选一个todo checkTodo(id){ this.todos.forEach((todo)=>{ if (todo.id === id) { todo.done = !todo.done } }) }, // 删除一个todo // deleteTodo(id){ // this.todos = this.todos.filter((todo)=>{ // return todo.id !== id // }) // }, // 使用pubsub需要在第一位参数接收一下消息名 deleteTodo(_, id){ this.todos = this.todos.filter((todo)=>{ return todo.id !== id }) }, // 全选or取消全选 checkAllTodo(done){ this.todos.forEach((todo)=>{ todo.done = done }) }, // 清除所有已经完成的todo clearAllTodo(){ this.todos = this.todos.filter((todo)=>{ return !todo.done }) } }, // 通过监视属性将todos存入浏览器本地存储 watch:{ todos:{ deep:true, handler(value){ localStorage.setItem('todos', JSON.stringify(value)) } } }, mounted(){ // 绑定全局事件 this.$bus.$on('checkTodo', this.checkTodo) // this.$bus.$on('deleteTodo', this.deleteTodo) // 使用pubsub订阅deleteTodo消息的数据 // 回调函数需要在第一位设置参数接收消息名 this.pubId = pubsub.subscribe('deleteTodo', this.deleteTodo) // this.pubId = pubsub.subscribe('deleteTodo', (msgName, data)=>{ // console.log(this) // console.log('有人发布了hello消息,hello消息的回调执行了', msgName, data) // this.deleteTodo(data) // }) }, beforeDestroy(){ // 解绑全局事件 this.$bus.$off('checkTodo') // this.$bus.$off('deleteTodo') // 使用pubsub取消订阅 pubsub.unsubscribe(this.pubId) }, }; </script> <style> /*base*/ body { background: #fff; } .btn { display: inline-block; padding: 4px 12px; margin-bottom: 0; font-size: 14px; line-height: 20px; text-align: center; vertical-align: middle; cursor: pointer; box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); border-radius: 4px; } .btn-danger { color: #fff; background-color: #da4f49; border: 1px solid #bd362f; } .btn-danger:hover { color: #fff; background-color: #bd362f; } .btn:focus { outline: none; } .todo-container { width: 600px; margin: 0 auto; } .todo-container .todo-wrap { padding: 10px; border: 1px solid #ddd; border-radius: 5px; } </style>
16. TodoList_nextTick
nextTick
- 语法:
this.$nextTick(回调函数)- 作用:在下一次 DOM 更新结束后执行其指定的回调。
- 什么时候用:当改变数据后,要基于更新后的新DOM进行某些操作时,要在nextTick所指定的回调函数中执行。
-
src\components\Item.vue
<template> <li> <label> <!-- 如下代码也能实现功能,但是不推荐,因为违反规则,修改了props --> <!-- <input type="checkbox" v-model="todo.done"> --> <input type="checkbox" :checked="todo.done" @change="handleCheck(todo.id)"/> <span v-show="!todo.isEdit">{{todo.title}}</span> <!-- 编辑模式时的输入框 --> <input type="text" placeholder="输入不能为空" v-show="todo.isEdit" :value="todo.title" @blur="handleBlur(todo, $event)" @keyup.enter="handleBlur(todo, $event)" ref="inputTitle" > </label> <button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button> <!-- 编辑按钮 --> <button class="btn btn-edit" v-show="!todo.isEdit" @click="handleEdit(todo)">编辑</button> </li> </template> <script> // 引入pubsub import pubsub from 'pubsub-js' export default { name: 'Item', // 声明接收todo、checkTodo、deleteTodo // props:['todo', 'checkTodo', 'deleteTodo'], props:['todo'], methods:{ // 勾选or取消勾选 handleCheck(id){ // 通知App组件将对应的todo对象的done值取反 // this.checkTodo(id) // 使用全局事件总线 this.$bus.$emit('checkTodo', id) }, // 删除 handleDelete(id){ if (confirm('确定删除吗?')) { // 通知App组件将对应的todo对象删除 // this.deleteTodo(id) // 使用全局事件总线 // this.$bus.$emit('deleteTodo', id) // 使用pubsub发布deleteTodo消息 pubsub.publish('deleteTodo', id) } }, // 编辑 handleEdit(todo){ if (todo.hasOwnProperty('isEdit')) { todo.isEdit = true }else{ console.log('@') this.$set(todo, 'isEdit', true) } this.$nextTick(function(){ this.$refs.inputTitle.focus() }) }, // 失去焦点回调(真正执行修改逻辑) handleBlur(todo, event){ todo.isEdit = false if (!event.target.value.trim()) { return alert('输入不能为空!') } this.$bus.$emit('updateTodo', todo.id, event.target.value) } } }; </script> <style lang="css" scoped> /*item*/ li { list-style: none; height: 36px; line-height: 36px; padding: 0 5px; border-bottom: 1px solid #ddd; } li label { float: left; cursor: pointer; } li label li input { vertical-align: middle; margin-right: 6px; position: relative; top: -1px; } li button { float: right; /* display: none; */ margin-top: 3px; } li:before { content: initial; } li:last-child { border-bottom: none; } </style> -
src\App.vue
<template> <div id="root"> <div class="todo-container"> <div class="todo-wrap"> <!-- <Header :addTodo="addTodos"></Header> --> <Header @addTodo="addTodos"></Header> <!-- <List :todos="todos" :checkTodo="checkTodo" :deleteTodo="deleteTodo"></List> --> <List :todos="todos"></List> <!-- <Footer :todos="todos" :checkAllTodo="checkAllTodo" :clearAllTodo="clearAllTodo"></Footer> --> <Footer :todos="todos" @checkAllTodo="checkAllTodo" @clearAllTodo="clearAllTodo"></Footer> </div> </div> </div> </template> <script> // 引入组件 import Header from './components/Header' import Footer from './components/Footer' import List from './components/List' // 引入pubsub import pubsub from 'pubsub-js' export default { name: 'App', components:{ Header, Footer, List }, data(){ return { // 由于todos是Header组件和Footer组件都在使用,所以放在App中(状态提升) // todos:[ // {id:'001', title:'抽烟', done:false}, // {id:'002', title:'喝酒', done:false}, // {id:'003', title:'烫头', done:true}, // ] // 从浏览器本地存储中获取todos todos:JSON.parse(localStorage.getItem('todos')) || [] } }, methods: { // 添加一个todo addTodos(todoObj) { this.todos.unshift(todoObj) }, // 勾选or取消勾选一个todo checkTodo(id){ this.todos.forEach((todo)=>{ if (todo.id === id) { todo.done = !todo.done } }) }, // 删除一个todo // deleteTodo(id){ // this.todos = this.todos.filter((todo)=>{ // return todo.id !== id // }) // }, // 使用pubsub需要在第一位参数接收一下消息名 deleteTodo(_, id){ this.todos = this.todos.filter((todo)=>{ return todo.id !== id }) }, // 全选or取消全选 checkAllTodo(done){ this.todos.forEach((todo)=>{ todo.done = done }) }, // 清除所有已经完成的todo clearAllTodo(){ this.todos = this.todos.filter((todo)=>{ return !todo.done }) }, // 更新一个todo updateTodo(id, title){ this.todos.forEach((todo)=>{ if (todo.id === id) { todo.title = title } }) } }, // 通过监视属性将todos存入浏览器本地存储 watch:{ todos:{ deep:true, handler(value){ localStorage.setItem('todos', JSON.stringify(value)) } } }, mounted(){ // 绑定全局事件 this.$bus.$on('checkTodo', this.checkTodo) // this.$bus.$on('deleteTodo', this.deleteTodo) // 使用pubsub订阅deleteTodo消息的数据 // 回调函数需要在第一位设置参数接收消息名 this.pubId = pubsub.subscribe('deleteTodo', this.deleteTodo) // this.pubId = pubsub.subscribe('deleteTodo', (msgName, data)=>{ // console.log(this) // console.log('有人发布了hello消息,hello消息的回调执行了', msgName, data) // this.deleteTodo(data) // }) // 绑定updateTodo事件 this.$bus.$on('updateTodo', this.updateTodo) }, beforeDestroy(){ // 解绑全局事件 this.$bus.$off('checkTodo') // this.$bus.$off('deleteTodo') // 使用pubsub取消订阅 pubsub.unsubscribe(this.pubId) // 解绑updateTodo事件 this.$bus.$off('updateTodo') }, }; </script> <style> /*base*/ body { background: #fff; } .btn { display: inline-block; padding: 4px 12px; margin-bottom: 0; font-size: 14px; line-height: 20px; text-align: center; vertical-align: middle; cursor: pointer; box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); border-radius: 4px; } .btn-danger { color: #fff; background-color: #da4f49; border: 1px solid #bd362f; } .btn-edit{ color: #fff; background-color: skyblue; border: 1px solid rgb(103, 159, 180); margin-right: 5px; } .btn-danger:hover { color: #fff; background-color: #bd362f; } .btn:focus { outline: none; } .todo-container { width: 600px; margin: 0 auto; } .todo-container .todo-wrap { padding: 10px; border: 1px solid #ddd; border-radius: 5px; } </style>
17. Vue封装的过度与动画
作用:在插入、更新或移除 DOM元素时,在合适的时候给元素添加样式类名。
图示:
写法:
准备好样式:
- 元素进入的样式:
- v-enter:进入的起点
- v-enter-active:进入过程中
- v-enter-to:进入的终点
- 元素离开的样式:
- v-leave:离开的起点
- v-leave-active:离开过程中
- v-leave-to:离开的终点
使用
<transition>包裹要过度的元素,并配置name属性:<transition name="hello"> <h1 v-show="isShow">你好啊!</h1> </transition>备注:若有多个元素需要过度,则需要使用:
<transition-group>,且每个元素都要指定key值。使用样式插件实现动画
安装animate.css
npm install animate.css --save增加标签属性
<transition-group appear name="animate__animated animate__bounce" enter-active-class="animate__bounceIn" leave-active-class="animate__backOutUp" > </transition-group>
- enter-active-class:进入动画class
- leave-active-class:离开动画class
- 可以从官网寻找需要的动画类型:https://animate.style/
**官网基础用法:**在安装animation .css之后,将animate__animated类添加到一个元素中,同时添加任意一个动画名称(不要忘记animate__前缀!):
<h1 class="animate__animated animate__bounce">An animated element</h1>
-
src\App.vue
<template> <div> <Test /> <Test2 /> <Test3 /> </div> </template> <script> import Test from './components/Test' import Test2 from './components/Test2' import Test3 from './components/Test3' export default { name: 'App', components:{ Test, Test2, Test3, }, }; </script> <style scoped> </style> -
src\components\Test.vue
<template> <div> <button @click="isShow = !isShow">显示/隐藏</button> <transition name="hello" appear> <h1 v-show="isShow">你好啊!</h1> </transition> </div> </template> <script> export default { name: 'Test', data() { return { isShow:true }; } }; </script> <style scoped> h1{ background-color: orange; } .hello-enter-active{ animation: atguigu 0.5s linear; } .hello-leave-active{ animation: atguigu 0.5s linear reverse; } @keyframes atguigu { from{ transform: translateX(-100%); } to{ transform: translateX(0px) } } </style> -
src\components\Test2.vue
<template> <div> <button @click="isShow = !isShow">显示/隐藏</button> <transition-group name="hello" appear> <h1 v-show="!isShow" key="1">你好啊!</h1> <h1 v-show="isShow" key="2">尚硅谷!</h1> </transition-group> </div> </template> <script> export default { name: 'Test2', data() { return { isShow:true }; } }; </script> <style scoped> h1{ background-color: orange; } /* 进入的起点、离开的终点 */ .hello-enter, hello-leave-to{ transform: translateX(-100%); } .hello-enter-active, hello-leave-active{ transition: 0.5s linear; } /* 进入的终点、离开的起点 */ .hello-enter-to, .hello-leave{ transform: translateX(0px); } </style> -
src\components\Test3.vue
<template> <div> <button @click="isShow = !isShow">显示/隐藏</button> <transition-group appear name="animate__animated animate__bounce" enter-active-class="animate__bounceIn" leave-active-class="animate__backOutUp" > <h1 v-show="!isShow" key="1">你好啊!</h1> <h1 v-show="isShow" key="2">尚硅谷!</h1> </transition-group> </div> </template> <script> // 引入animate.css样式库 import 'animate.css' export default { name: 'Test3', data() { return { isShow:true }; } }; </script> <style scoped> h1{ background-color: orange; } </style>
18. TodoList_动画
-
src\components\List.vue
<template> <ul class="todo-main"> <!-- <Item v-for="todoObj in todos" :key="todoObj.id" :todo="todoObj" :checkTodo="checkTodo" :deleteTodo="deleteTodo" /> --> <!-- 使用全局事件总线就不需要再进行参数传递 --> <!-- 增加动画 --> <transition-group name="todo" appear> <Item v-for="todoObj in todos" :key="todoObj.id" :todo="todoObj" /> </transition-group> </ul> </template> <script> // 引入Item import Item from './Item' export default { name: 'List', components:{ Item }, // 声明接收App传递过来的数据,其中todos是自己用的,checkTodo和deleteTodo是给自组建Item用的 // props:['todos', 'checkTodo', 'deleteTodo'] // 用全局事件总线就不需要再进行参数传递 props:['todos'] }; </script> <style lang="css" scoped> /*main*/ .todo-main { margin-left: 0px; border: 1px solid #ddd; border-radius: 2px; padding: 0px; } .todo-empty { height: 40px; line-height: 40px; border: 1px solid #ddd; border-radius: 2px; padding-left: 5px; margin-top: 10px; } /* 自定义动画 */ .todo-enter-active{ animation: atguigu 0.5s linear; } .todo-leave-active{ animation: atguigu 0.5s linear reverse; } @keyframes atguigu { from{ transform: translateX(100%); } to{ transform: translateX(0px); } } </style>
19. vue脚手架配置代理
-
安装axios
npm install vue-axios --save
方法一
在vue.config.js中添加如下配置:devServer:{ proxy:"http://localhost:5000" }说明:
- 优点:配置简单,请求资源时直接发给前端(8080)即可。
- 缺点:不能配置多个代理,不能灵活的控制请求是否走代理。
- 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器 (优先匹配前端资源)
方法二
编写vue.config.js配置具体代理规则:module.exports = { devServer: { proxy: { '/api1': {// 匹配所有以 '/api1'开头的请求路径 target: 'http://localhost:5000',// 代理目标的基础路径 changeOrigin: true, pathRewrite: {'^/api1': ''} }, '/api2': {// 匹配所有以 '/api2'开头的请求路径 target: 'http://localhost:5001',// 代理目标的基础路径 changeOrigin: true, pathRewrite: {'^/api2': ''} } } } } /* changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000 changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080 changeOrigin默认值为true */说明:
- 优点:可以配置多个代理,且可以灵活的控制请求是否走代理。
- 缺点:配置略微繁琐,请求资源时必须加前缀。
-
vue.config.js
const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ transpileDependencies: true, // 关闭语法检查 lintOnSave: false, // 开启代理服务器(方法一) // devServer: { // proxy: 'http://localhost:5000' // } // 开启代理服务器(方法二) devServer: { proxy: { '/atguigu': { target: 'http://localhost:5000', pathRewrite: { '^/atguigu':'', // // 用于支持websocket // ws: true, // // 用于控制请求头中的host值 // changeOrigin: true } }, '/demo': { target: 'http://localhost:5001', pathRewrite: { '^/demo': '', // // 用于支持websocket // ws: true, // // 用于控制请求头中的host值 // changeOrigin: true } } } } }) -
src\App.vue
<template> <div> <button @click="getStudents">获取学生信息</button> <button @click="getCars">获取汽车信息</button> </div> </template> <script> import axios from 'axios' export default { name: 'App', methods:{ // getStudents(){ // axios.get('http://localhost:8080/students').then( // response => { // console.log('请求成功了',response.data) // }, // error => { // console.log('请求失败了',error.message) // } // ) // }, getStudents(){ axios.get('http://localhost:8080/atguigu/students').then( response => { console.log('请求成功了',response.data) }, error => { console.log('请求失败了',error.message) } ) }, getCars(){ axios.get('http://localhost:8080/demo/cars').then( response => { console.log('请求成功了',response.data) }, error => { console.log('请求失败了',error.message) } ) } } }; </script> <style scoped> </style>
20. GitHub搜索案例
-
src\App.vue
<template> <div class="container"> <SearchBox /> <SearchList /> </div> </template> <script> import SearchBox from './components/SearchBox' import SearchList from './components/SearchList' export default { name: 'App', components:{ SearchBox, SearchList } }; </script> <style scoped> </style> -
src\components\SearchList.vue
<template> <div class="row"> <!-- 展示用户列表 --> <div class="card" v-show="info.users.length" v-for="user in info.users" :key="user.login"> <a :href="user.html_url" target="_blank"> <img :src="user.avatar_url" style='width: 100px'/> </a> <p class="card-text">{{user.login}}</p> </div> <!-- 展示欢迎词 --> <h1 v-show="info.isFirst">欢迎使用</h1> <!-- 展示加载中 --> <h1 v-show="info.isLoading">加载中</h1> <!-- 展示错误信息 --> <h1 v-show="info.errMsg">{{info.errMsg}}</h1> </div> </template> <script> export default { name: 'SearchList', data(){ return { info: { isFirst: true, isLoading: false, errMsg:'', users:[] } } }, mounted(){ this.$bus.$on('updateListData', (dataObj)=>{ this.info = {...this.info, ...dataObj} }) } }; </script> <style scoped> .album { min-height: 50rem; /* Can be removed; just added for demo purposes */ padding-top: 3rem; padding-bottom: 3rem; background-color: #f7f7f7; } .card { float: left; width: 33.333%; padding: .75rem; margin-bottom: 2rem; border: 1px solid #efefef; text-align: center; } .card > img { margin-bottom: .75rem; border-radius: 100px; } .card-text { font-size: 85%; } </style> -
src\components\SearchBox.vue
<template> <section class="jumbotron"> <h3 class="jumbotron-heading">Search Github Users</h3> <div> <input type="text" placeholder="enter the name you search" v-model="keyWord"/> <button @click="searchUsers">Search</button> </div> </section> </template> <script> // 引入axios import axios from 'axios' export default { name: 'SearchBox', data(){ return { keyWord:'' } }, methods:{ searchUsers(){ // 请求前刷新SearchList的数据 this.$bus.$emit('updateListData', {isLoading:true, errMsg:'', users:[], isFirst:false}) axios.get(`https://api.github.com/search/users?q=${this.keyWord}`).then( response => { console.log('请求成功了!') // 请求成功后更新SearchList的数据 this.$bus.$emit('updateListData', {isLoading:false, errMsg:'', users:response.data.items, isFirst:false}) }, error => { this.$bus.$emit('updateListData', {isLoading:false, errMsg:error.message, users:[], isFirst:false}) } ) } } }; </script> <style scoped> </style>
21. GitHub搜索案例_vue-resource
-
vue-resource作用与用法和axios相同,vue1.0中常用,了解即可,现在已经很少用了
-
使用该插件后,vc中会多一个$http,用法和axios相同

-
src\main.js
/* 该文件是整个项目的入口文件 */ // 引入Vue import Vue from 'vue' // 引入App组件,它是所有组件的父组件 import App from './App.vue' // 引入vue-resource插件 import vueResource from 'vue-resource' // 关闭Vue的生产提示 Vue.config.productionTip = false // 使用vue-resource Vue.use(vueResource) // 创建Vue实例对象——vm new Vue({ el:'#app', render: h => h(App), beforeCreate(){ // 安装全局事件总线 Vue.prototype.$bus = this } }) -
src\components\SearchBox.vue
<template> <section class="jumbotron"> <h3 class="jumbotron-heading">Search Github Users</h3> <div> <input type="text" placeholder="enter the name you search" v-model="keyWord"/> <button @click="searchUsers">Search</button> </div> </section> </template> <script> // 引入axios // import axios from 'axios' export default { name: 'SearchBox', data(){ return { keyWord:'' } }, methods:{ searchUsers(){ // 查看this(即vc)中多了一个$http console.log(this) // 请求前刷新SearchList的数据 this.$bus.$emit('updateListData', {isLoading:true, errMsg:'', users:[], isFirst:false}) // 将axios改为this.$http this.$http.get(`https://api.github.com/search/users?q=${this.keyWord}`).then( response => { console.log('请求成功了!') // 请求成功后更新SearchList的数据 this.$bus.$emit('updateListData', {isLoading:false, errMsg:'', users:response.data.items, isFirst:false}) }, error => { this.$bus.$emit('updateListData', {isLoading:false, errMsg:error.message, users:[], isFirst:false}) } ) } } }; </script> <style scoped> </style>
22. 插槽
作用:让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于 父组件 ===> 子组件 。
分类:默认插槽、具名插槽、作用域插槽
使用方式:
默认插槽:
父组件中: <Category> <div>html结构1</div> </Category> 子组件中: <template> <div> <!-- 定义插槽 --> <slot>插槽默认内容...</slot> </div> </template>具名插槽:
父组件中: <Category> <template slot="center"> <div>html结构1</div> </template> <template v-slot:footer> <div>html结构2</div> </template> </Category> 子组件中: <template> <div> <!-- 定义插槽 --> <slot name="center">插槽默认内容...</slot> <slot name="footer">插槽默认内容...</slot> </div> </template>作用域插槽:
理解:数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定。(games数据在Category组件中,但使用数据所遍历出来的结构由App组件决定)
具体编码:
父组件中: <Category> <template scope="scopeData"> <!-- 生成的是ul列表 --> <ul> <li v-for="g in scopeData.games" :key="g">{{g}}</li> </ul> </template> </Category> <Category> <template slot-scope="scopeData"> <!-- 生成的是h4标题 --> <h4 v-for="g in scopeData.games" :key="g">{{g}}</h4> </template> </Category> 子组件中: <template> <div> <slot :games="games"></slot> </div> </template> <script> export default { name:'Category', props:['title'], //数据在子组件自身 data() { return { games:['红色警戒','穿越火线','劲舞团','超级玛丽'] } }, } </script>
默认插槽
-
src\components\Category.vue
<<template> <div class="category"> <h3>{{title}}</h3> <!-- 定义一个插槽(挖个坑,等着组件的使用者进行填充) --> <slot>我是一些默认值,当使用者没有传递具体结构时,我会出现</slot> </div> </template> <script> export default { name: 'Category', props:['title'], }; </script> <style scoped> .category{ background-color: skyblue; width: 200px; height: 300px; } h3{ text-align: center; background-color: orange; } video{ width: 100%; } img{ width: 100%; } </style> -
src\App.vue
<template> <div class="container"> <Category title="美食"> <ul> <li v-for="(f, index) in foods" :key="index">{{f}}</li> </ul> <img src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt=""> </Category> <Category title="游戏"> <ul> <li v-for="(g, index) in games" :key="index">{{g}}</li> </ul> </Category> <Category title="电影"> <ul> <li v-for="(f, index) in films" :key="index">{{f}}</li> </ul> <video controls src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video> </Category> </div> </template> <script> import Category from './components/Category' export default { name: 'App', components:{ Category }, data(){ return { foods:['火锅','烧烤','小龙虾','牛排'], games:['红色警戒','穿越火线','劲舞团','超级玛丽'], films:['《教父》','《拆弹专家》','《你好,李焕英》','《尚硅谷》'] } } }; </script> <style scoped> .container{ display: flex; justify-content: space-around; } </style>
具名插槽
-
src\components\Category.vue
<<template> <div class="category"> <h3>{{title}}</h3> <!-- 定义一个插槽(挖个坑,等着组件的使用者进行填充) --> <!-- <slot>我是一些默认值,当使用者没有传递具体结构时,我会出现</slot> --> <slot name="center">我是一些默认值,当使用者没有传递具体结构时,我会出现1</slot> <slot name="footer">我是一些默认值,当使用者没有传递具体结构时,我会出现2</slot> </div> </template> <script> export default { name: 'Category', props:['title'], }; </script> <style scoped> .category{ background-color: skyblue; width: 200px; height: 300px; } h3{ text-align: center; background-color: orange; } video{ width: 100%; } img{ width: 100%; } </style> -
src\App.vue
<template> <div class="container"> <Category title="美食"> <!-- <ul> <li v-for="(f, index) in foods" :key="index">{{f}}</li> </ul> --> <img slot="center" src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt=""> <a slot="footer" href="http://www.atguigu.com">更多美食</a> </Category> <Category title="游戏"> <ul slot="center"> <li v-for="(g, index) in games" :key="index">{{g}}</li> </ul> <div class="foot" slot="footer"> <a href="http://www.atguigu.com">单机游戏</a> <a href="http://www.atguigu.com">网络游戏</a> </div> </Category> <Category title="电影"> <!-- <ul> <li v-for="(f, index) in films" :key="index">{{f}}</li> </ul> --> <video slot="center" controls src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video> <template v-slot:footer> <div class="foot"> <a href="http://www.atguigu.com">经典</a> <a href="http://www.atguigu.com">热门</a> <a href="http://www.atguigu.com">推荐</a> </div> <h4>欢迎前来观影</h4> </template> </Category> </div> </template> <script> import Category from './components/Category' export default { name: 'App', components:{ Category }, data(){ return { foods:['火锅','烧烤','小龙虾','牛排'], games:['红色警戒','穿越火线','劲舞团','超级玛丽'], films:['《教父》','《拆弹专家》','《你好,李焕英》','《尚硅谷》'] } } }; </script> <style scoped> .container, .foot{ display: flex; justify-content: space-around; } h4{ text-align: center; } </style>
作用域插槽
-
src\components\Category.vue
<<template> <div class="category"> <h3>{{title}}分类</h3> <slot :games="games" msg="hello">我是一些默认内容</slot> </div> </template> <script> export default { name: 'Category', props:['title'], data(){ return { games:['红色警戒','穿越火线','劲舞团','超级玛丽'], } } }; </script> <style scoped> .category{ background-color: skyblue; width: 200px; height: 300px; } h3{ text-align: center; background-color: orange; } video{ width: 100%; } img{ width: 100%; } </style> -
src\App.vue
<template> <div class="container"> <Category title="游戏"> <template scope="atguigu"> <ul> <li v-for="(g, index) in atguigu.games" :key="index">{{g}}</li> </ul> </template> </Category> <Category title="游戏"> <template scope="{games}"> <ol> <li style="color:red" v-for="(g, index) in games" :key="index">{{g}}</li> </ol> </template> </Category> <Category title="游戏"> <template slot-scope="{games}"> <h4 v-for="(g, index) in games" :key="index">{{g}}</h4> </template> </Category> </div> </template> <script> import Category from './components/Category' export default { name: 'App', components:{ Category } }; </script> <style scoped> .container, .foot{ display: flex; justify-content: space-around; } h4{ text-align: center; } </style>
23. 求和案例_纯vue版
-
src\App.vue
<template> <div> <Count /> </div> </template> <script> import Count from './components/Count' export default { name: 'App', components:{ Count } }; </script> <style scoped> </style> -
src\components\Count.vue
<<template> <div> <h1>当前求和为:{{sum}}</h1> <!-- v-model.number限制value的数据类型为数值 --> <select v-model.number="n"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <button @click="increment">+</button> <button @click="decrement">-</button> <button @click="oddIncrement">当前求和为奇数再加</button> <button @click="waitIncrement">等一等再加</button> </div> </template> <script> export default { name: 'Count', data(){ return { sum:0, n:1 } }, methods:{ // 加法 increment(){ this.sum += this.n }, // 减法 decrement(){ this.sum -= this.n }, // sum为奇数再加 oddIncrement(){ if (this.sum % 2) { this.sum += this.n } }, // 等1s再加 waitIncrement(){ setTimeout(()=>{ this.sum += this.n }, 1000) } } }; </script> <style lang="css" scoped> button{ margin-left: 5px; } </style>
Vuex
1.概念
在Vue中实现集中式状态(数据)管理的一个Vue插件,对vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信。

2.何时使用?
多个组件需要共享数据时
3.搭建vuex环境
安装vuex插件
vue默认vue3版本,vuex默认vuex4版本,vuex4只能在vue3中使用,
在vue2中能使用vuex3,那么不能默认下载最新的版本
npm install vuex@3 --save创建文件:
src/store/index.js//引入Vue核心库 import Vue from 'vue' //引入Vuex import Vuex from 'vuex' //应用Vuex插件 Vue.use(Vuex) //准备actions对象——响应组件中用户的动作 const actions = {} //准备mutations对象——修改state中的数据 const mutations = {} //准备state对象——保存具体的数据 const state = {} //创建并暴露store export default new Vuex.Store({ actions, mutations, state })在
main.js中创建vm时传入store配置项...... //引入store import store from './store' ...... //创建vm new Vue({ el:'#app', render: h => h(App), store })
4.基本使用
初始化数据、配置
actions、配置mutations,操作文件store.js//引入Vue核心库 import Vue from 'vue' //引入Vuex import Vuex from 'vuex' //引用Vuex Vue.use(Vuex) const actions = { //响应组件中加的动作 jia(context,value){ // console.log('actions中的jia被调用了',miniStore,value) context.commit('JIA',value) }, } const mutations = { //执行加 JIA(state,value){ // console.log('mutations中的JIA被调用了',state,value) state.sum += value } } //初始化数据 const state = { sum:0 } //创建并暴露store export default new Vuex.Store({ actions, mutations, state, })组件中读取vuex中的数据:
$store.state.sum组件中修改vuex中的数据:
$store.dispatch('action中的方法名',数据)或$store.commit('mutations中的方法名',数据)备注:若没有网络请求或其他业务逻辑,组件中也可以越过actions,即不写
dispatch,直接编写commit
24. 求和案例_vuex版
-
src\store\index.js
// 该文件用于创建Vuex中最为核心的store // 引入Vue import Vue from 'vue' // 应用Vuex插件 import Vuex from 'vuex' // 使用Vuex插件 Vue.use(Vuex) // 准备actions——用于响应组件中的动作 const actions = { // 由于没有进行多余操作,外界可以直接调用commit函数,使用mutations进行处理 // jia(context, value){ // console.log('actions中的jia被调用了') // context.commit('JIA', value) // }, // jian(context, value){ // console.log('actions中的jian被调用了') // context.commit('JIAN', value) // }, jiaOdd(context, value){ console.log('actions中的jiaOdd被调用了') if (context.state.sum % 2) { context.commit('JIA', value) } }, jiaWait(context, value){ console.log('actions中的jiaWait被调用了') setTimeout(()=>{ context.commit('JIA', value) }, 1000) }, } // 准备mutations——用于操作数据(state) const mutations = { JIA(state, value){ console.log('mutations中的JIA被调用了') state.sum += value }, JIAN(state, value){ console.log('mutations中的JIAN被调用了') state.sum -= value }, } // 准备state——用于存储数据 const state = { // 当前的和 sum:0 } // 创建并暴露store export default new Vuex.Store({ actions, mutations, state, }) -
src\main.js
/* 该文件是整个项目的入口文件 */ // 引入Vue import Vue from 'vue' // 引入App组件,它是所有组件的父组件 import App from './App.vue' // 引入store import store from './store' // 关闭Vue的生产提示 Vue.config.productionTip = false // 创建Vue实例对象——vm new Vue({ el:'#app', render: h => h(App), store, beforeCreate(){ // 安装全局事件总线 Vue.prototype.$bus = this } }) -
src\App.vue
<template> <div> <Count /> </div> </template> <script> import Count from './components/Count' export default { name: 'App', components:{ Count }, mounted(){ console.log('App',this) } }; </script> <style scoped> </style> -
src\components\Count.vue
<<template> <div> <h1>当前求和为:{{$store.state.sum}}</h1> <!-- v-model.number限制value的数据类型为数值 --> <select v-model.number="n"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <button @click="increment">+</button> <button @click="decrement">-</button> <button @click="oddIncrement">当前求和为奇数再加</button> <button @click="waitIncrement">等一等再加</button> </div> </template> <script> export default { name: 'Count', data(){ return { // 求和结果 // sum:0, // 用户选择的数字 n:1 } }, methods:{ // 加法 increment(){ this.$store.commit('JIA', this.n) }, // 减法 decrement(){ this.$store.commit('JIAN', this.n) }, // sum为奇数再加 oddIncrement(){ this.$store.dispatch('jiaOdd', this.n) }, // 等1s再加 waitIncrement(){ this.$store.dispatch('jiaWait', this.n) } }, mounted(){ console.log('Count',this) } }; </script> <style lang="css" scoped> button{ margin-left: 5px; } </style>
5.getters的使用
概念:当state中的数据需要经过加工后再使用时,可以使用getters加工。
在
store.js中追加getters配置...... const getters = { bigSum(state){ return state.sum * 10 } } //创建并暴露store export default new Vuex.Store({ ...... getters })组件中读取数据:
$store.getters.bigSum
25. 求和案例_getters
-
src\store\index.js
// 该文件用于创建Vuex中最为核心的store // 引入Vue import Vue from 'vue' // 应用Vuex插件 import Vuex from 'vuex' // 使用Vuex插件 Vue.use(Vuex) // 准备actions——用于响应组件中的动作 const actions = { // 由于没有进行多余操作,外界可以直接调用commit函数,使用mutations进行处理 // jia(context, value){ // console.log('actions中的jia被调用了') // context.commit('JIA', value) // }, // jian(context, value){ // console.log('actions中的jian被调用了') // context.commit('JIAN', value) // }, jiaOdd(context, value){ console.log('actions中的jiaOdd被调用了') if (context.state.sum % 2) { context.commit('JIA', value) } }, jiaWait(context, value){ console.log('actions中的jiaWait被调用了') setTimeout(()=>{ context.commit('JIA', value) }, 1000) }, } // 准备mutations——用于操作数据(state) const mutations = { JIA(state, value){ console.log('mutations中的JIA被调用了') state.sum += value }, JIAN(state, value){ console.log('mutations中的JIAN被调用了') state.sum -= value }, } // 准备state——用于存储数据 const state = { // 当前的和 sum:0 } // 准备getters——用于将state中的数据进行加工 const getters = { bigSum(state){ return state.sum * 10 } } // 创建并暴露store export default new Vuex.Store({ actions, mutations, state, getters, }) -
src\components\Count.vue
<<template> <div> <h1>当前求和为:{{$store.state.sum}}</h1> <h3>当前求和放大10倍为:{{$store.getters.bigSum}}</h3> <!-- v-model.number限制value的数据类型为数值 --> <select v-model.number="n"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <button @click="increment">+</button> <button @click="decrement">-</button> <button @click="oddIncrement">当前求和为奇数再加</button> <button @click="waitIncrement">等一等再加</button> </div> </template> <script> export default { name: 'Count', data(){ return { // 求和结果 // sum:0, // 用户选择的数字 n:1 } }, methods:{ // 加法 increment(){ this.$store.commit('JIA', this.n) }, // 减法 decrement(){ this.$store.commit('JIAN', this.n) }, // sum为奇数再加 oddIncrement(){ this.$store.dispatch('jiaOdd', this.n) }, // 等1s再加 waitIncrement(){ this.$store.dispatch('jiaWait', this.n) } }, mounted(){ console.log('Count',this.$store) } }; </script> <style lang="css" scoped> button{ margin-left: 5px; } </style>
6.四个map方法的使用
mapState方法:用于帮助我们映射
state中的数据为计算属性computed: { //借助mapState生成计算属性:sum、school、subject(对象写法) ...mapState({sum:'sum',school:'school',subject:'subject'}), //借助mapState生成计算属性:sum、school、subject(数组写法) ...mapState(['sum','school','subject']), },mapGetters方法:用于帮助我们映射
getters中的数据为计算属性computed: { //借助mapGetters生成计算属性:bigSum(对象写法) ...mapGetters({bigSum:'bigSum'}), //借助mapGetters生成计算属性:bigSum(数组写法) ...mapGetters(['bigSum']) },mapActions方法:用于帮助我们生成与
actions对话的方法,即:包含$store.dispatch(xxx)的函数methods:{ //靠mapActions生成:incrementOdd、incrementWait(对象形式) ...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'}) //靠mapActions生成:incrementOdd、incrementWait(数组形式) ...mapActions(['jiaOdd','jiaWait']) }mapMutations方法:用于帮助我们生成与
mutations对话的方法,即:包含$store.commit(xxx)的函数methods:{ //靠mapActions生成:increment、decrement(对象形式) ...mapMutations({increment:'JIA',decrement:'JIAN'}), //靠mapMutations生成:JIA、JIAN(对象形式) ...mapMutations(['JIA','JIAN']), }备注:mapActions与mapMutations使用时,若需要传递参数需要:在模板中绑定事件时传递好参数,否则参数是事件对象。
注意:加上 … 的意思是把对象展开
26. 求和案例_mapState与mapGetters
-
src\store\index.js
// 该文件用于创建Vuex中最为核心的store // 引入Vue import Vue from 'vue' // 应用Vuex插件 import Vuex from 'vuex' // 使用Vuex插件 Vue.use(Vuex) // 准备actions——用于响应组件中的动作 const actions = { // 由于没有进行多余操作,外界可以直接调用commit函数,使用mutations进行处理 // jia(context, value){ // console.log('actions中的jia被调用了') // context.commit('JIA', value) // }, // jian(context, value){ // console.log('actions中的jian被调用了') // context.commit('JIAN', value) // }, jiaOdd(context, value){ console.log('actions中的jiaOdd被调用了') if (context.state.sum % 2) { context.commit('JIA', value) } }, jiaWait(context, value){ console.log('actions中的jiaWait被调用了') setTimeout(()=>{ context.commit('JIA', value) }, 1000) }, } // 准备mutations——用于操作数据(state) const mutations = { JIA(state, value){ console.log('mutations中的JIA被调用了') state.sum += value }, JIAN(state, value){ console.log('mutations中的JIAN被调用了') state.sum -= value }, } // 准备state——用于存储数据 const state = { // 当前的和 sum:0, school:'尚硅谷', subject:'前端' } // 准备getters——用于将state中的数据进行加工 const getters = { bigSum(state){ return state.sum * 10 } } // 创建并暴露store export default new Vuex.Store({ actions, mutations, state, getters, }) -
src\components\Count.vue
<<template> <div> <!-- <h1>当前求和为:{{$store.state.sum}}</h1> --> <!-- <h1>当前求和为:{{he}}</h1> --> <h1>当前求和为:{{sum}}</h1> <!-- <h1>我在{{xuexiao}},学习{{xueke}}</h1> --> <h1>我在{{school}},学习{{subject}}</h1> <!-- <h3>当前求和放大10倍为:{{$store.getters.bigSum}}</h3> --> <h3>当前求和放大10倍为:{{bigSum}}</h3> <!-- v-model.number限制value的数据类型为数值 --> <select v-model.number="n"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <button @click="increment">+</button> <button @click="decrement">-</button> <button @click="oddIncrement">当前求和为奇数再加</button> <button @click="waitIncrement">等一等再加</button> </div> </template> <script> // 引入mapState和mapGetters import { mapState, mapGetters } from "vuex"; export default { name: 'Count', data(){ return { // 求和结果 // sum:0, // 用户选择的数字 n:1 } }, computed:{ // 自己写计算属性 // state // sum(){ // return this.$store.state.sum // }, // school(){ // return this.$store.state.school // }, // subject(){ // return this.$store.state.subject // }, // 使用mapState生成计算属性,从state中读取数据(对象写法) // ...mapState({he:'sum', xuexiao:'school', xueke:'subject'}), // 使用mapState生成计算属性,从state中读取数据(当key和value相同时,可以用数组写法) ...mapState(['sum', 'school', 'subject']), // getters // bigSum(){ // return this.$store.getters.bigSum // }, // 使用mapGetters生成计算属性,从getters中读取数据(对象写法) // ...mapGetters({bigSum:'bigSum'}), // 使用mapGetters生成计算属性,从getters中读取数据(当key和value相同时,可以用数组写法) ...mapGetters(['bigSum']) }, methods:{ // 加法 increment(){ this.$store.commit('JIA', this.n) }, // 减法 decrement(){ this.$store.commit('JIAN', this.n) }, // sum为奇数再加 oddIncrement(){ this.$store.dispatch('jiaOdd', this.n) }, // 等1s再加 waitIncrement(){ this.$store.dispatch('jiaWait', this.n) } }, mounted(){ console.log('Count',this.$store) } }; </script> <style lang="css" scoped> button{ margin-left: 5px; } </style>
27. 求和案例_mapMutations与mapActions
-
src\components\Count.vue
<<template> <div> <!-- <h1>当前求和为:{{$store.state.sum}}</h1> --> <!-- <h1>当前求和为:{{he}}</h1> --> <h1>当前求和为:{{sum}}</h1> <!-- <h1>我在{{xuexiao}},学习{{xueke}}</h1> --> <h1>我在{{school}},学习{{subject}}</h1> <!-- <h3>当前求和放大10倍为:{{$store.getters.bigSum}}</h3> --> <h3>当前求和放大10倍为:{{bigSum}}</h3> <!-- v-model.number限制value的数据类型为数值 --> <select v-model.number="n"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <!-- <button @click="increment">+</button> <button @click="decrement">-</button> <button @click="oddIncrement">当前求和为奇数再加</button> <button @click="waitIncrement">等一等再加</button> --> <!-- mapActions与mapMutations使用时,若需要传递参数需要:在模板中绑定事件时传递好参数,否则参数是事件对象。 --> <!-- <button @click="increment(n)">+</button> <button @click="decrement(n)">-</button> <button @click="oddIncrement(n)">当前求和为奇数再加</button> <button @click="waitIncrement(n)">等一等再加</button> --> <button @click="JIA(n)">+</button> <button @click="JIAN(n)">-</button> <button @click="jiaOdd(n)">当前求和为奇数再加</button> <button @click="jiaWait(n)">等一等再加</button> </div> </template> <script> // 引入mapState和mapGetters、mapActions和mapMutations import { mapState, mapGetters, mapActions, mapMutations } from "vuex"; export default { name: 'Count', data(){ return { // 求和结果 // sum:0, // 用户选择的数字 n:1 } }, computed:{ // 自己写计算属性 // state // sum(){ // return this.$store.state.sum // }, // school(){ // return this.$store.state.school // }, // subject(){ // return this.$store.state.subject // }, // 使用mapState生成计算属性,从state中读取数据(对象写法) // ...mapState({he:'sum', xuexiao:'school', xueke:'subject'}), // 使用mapState生成计算属性,从state中读取数据(当key和value相同时,可以用数组写法) ...mapState(['sum', 'school', 'subject']), // getters // bigSum(){ // return this.$store.getters.bigSum // }, // 使用mapGetters生成计算属性,从getters中读取数据(对象写法) // ...mapGetters({bigSum:'bigSum'}), // 使用mapGetters生成计算属性,从getters中读取数据(当key和value相同时,可以用数组写法) ...mapGetters(['bigSum']) }, methods:{ // 自己写方法 // mapMutations // 加法 // increment(){ // this.$store.commit('JIA', this.n) // }, // // 减法 // decrement(){ // this.$store.commit('JIAN', this.n) // }, // 使用mapMutations生成对应的方法,方法会调用commit去联系mutations(对象写法) // ...mapMutations({increment:'JIA', decrement:'JIAN'}), // 使用mapMutations生成对应的方法,方法会调用commit去联系mutations(当key和value相同时,可以用数组写法) ...mapMutations(['JIA', 'JIAN']), // actions // 自己写方法 // sum为奇数再加 // oddIncrement(){ // this.$store.dispatch('jiaOdd', this.n) // }, // // 等1s再加 // waitIncrement(){ // this.$store.dispatch('jiaWait', this.n) // }, // 使用mapActions生成对应的方法,方法会调用dispatch去联系actions(对象写法) // ...mapActions({oddIncrement:'jiaOdd', waitIncrement:'jiaWait'}), // 使用mapMutations生成对应的方法,方法会调用dispatch去联系actions(当key和value相同时,可以用数组写法) ...mapActions(['jiaOdd','jiaWait']), }, mounted(){ console.log(mapState({he:'sum', xuexiao:'school', xueke:'subject'})) console.log('Count',this.$store) } }; </script> <style lang="css" scoped> button{ margin-left: 5px; } </style>
28. 求和案例_多组件共享数据
-
src\store\index.js
// 该文件用于创建Vuex中最为核心的store // 引入Vue import Vue from 'vue' // 应用Vuex插件 import Vuex from 'vuex' // 使用Vuex插件 Vue.use(Vuex) // 准备actions——用于响应组件中的动作 const actions = { // 由于没有进行多余操作,外界可以直接调用commit函数,使用mutations进行处理 // jia(context, value){ // console.log('actions中的jia被调用了') // context.commit('JIA', value) // }, // jian(context, value){ // console.log('actions中的jian被调用了') // context.commit('JIAN', value) // }, jiaOdd(context, value){ console.log('actions中的jiaOdd被调用了') if (context.state.sum % 2) { context.commit('JIA', value) } }, jiaWait(context, value){ console.log('actions中的jiaWait被调用了') setTimeout(()=>{ context.commit('JIA', value) }, 1000) }, } // 准备mutations——用于操作数据(state) const mutations = { JIA(state, value){ console.log('mutations中的JIA被调用了') state.sum += value }, JIAN(state, value){ console.log('mutations中的JIAN被调用了') state.sum -= value }, ADD_PERSON(state, value){ console.log('mutations中的ADD_PERSON被调用了') state.personList.unshift(value) } } // 准备state——用于存储数据 const state = { // 当前的和 sum:0, school:'尚硅谷', subject:'前端', personList:[ {id:'001', name:'张三'} ] } // 准备getters——用于将state中的数据进行加工 const getters = { bigSum(state){ return state.sum * 10 } } // 创建并暴露store export default new Vuex.Store({ actions, mutations, state, getters, }) -
src\App.vue
<template> <div> <Count /> <Person /> </div> </template> <script> import Count from './components/Count' import Person from './components/Person' export default { name: 'App', components:{ Count, Person }, mounted(){ // console.log('App',this) } }; </script> <style scoped> </style> -
src\components\Count.vue
<<template> <div> <!-- <h1>当前求和为:{{$store.state.sum}}</h1> --> <!-- <h1>当前求和为:{{he}}</h1> --> <h1>当前求和为:{{sum}}</h1> <!-- <h3>当前求和放大10倍为:{{$store.getters.bigSum}}</h3> --> <h3>当前求和放大10倍为:{{bigSum}}</h3> <!-- <h1>我在{{xuexiao}},学习{{xueke}}</h1> --> <h3>我在{{school}},学习{{subject}}</h3> <h3>Person组件的总人数是:{{personList.length}}</h3> <!-- v-model.number限制value的数据类型为数值 --> <select v-model.number="n"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <!-- mapActions与mapMutations使用时,若需要传递参数需要:在模板中绑定事件时传递好参数,否则参数是事件对象。 --> <button @click="increment(n)">+</button> <button @click="decrement(n)">-</button> <button @click="oddIncrement(n)">当前求和为奇数再加</button> <button @click="waitIncrement(n)">等一等再加</button> </div> </template> <script> // 引入mapState和mapGetters、mapActions和mapMutations import { mapState, mapGetters, mapActions, mapMutations } from "vuex"; export default { name: 'Count', data(){ return { // 用户选择的数字 n:1 } }, computed:{ // 使用mapState生成计算属性,从state中读取数据(当key和value相同时,可以用数组写法) ...mapState(['sum', 'school', 'subject', 'personList']), // 使用mapGetters生成计算属性,从getters中读取数据(当key和value相同时,可以用数组写法) ...mapGetters(['bigSum']) }, methods:{ // 使用mapMutations生成对应的方法,方法会调用commit去联系mutations(对象写法) ...mapMutations({increment:'JIA', decrement:'JIAN'}), // 使用mapActions生成对应的方法,方法会调用dispatch去联系actions(对象写法) ...mapActions({oddIncrement:'jiaOdd', waitIncrement:'jiaWait'}), }, }; </script> <style lang="css" scoped> button{ margin-left: 5px; } </style> -
src\components\Person.vue
<<template> <div> <h1>人员列表</h1> <h3>Count组件求和为:{{sum}}</h3> <input type="text" placeholder="请输入名字" v-model="name" @keyup.enter="add"> <button @click="add">添加</button> <ul> <li v-for="p in personList" :key="p.id">{{p.name}}</li> </ul> </div> </template> <script> import {nanoid} from 'nanoid' export default { name: 'Person', data(){ return { name:'' } }, computed:{ personList(){ return this.$store.state.personList }, sum(){ return this.$store.state.sum } }, methods:{ add(){ const personObj = {id:nanoid(), name:this.name} this.$store.commit('ADD_PERSON', personObj) this.name = '' } }, }; </script> <style lang="css" scoped> button{ margin-left: 5px; } </style>
7.模块化+命名空间
目的:让代码更好维护,让多种数据分类更加明确。
修改
store.jsconst countAbout = { namespaced:true,//开启命名空间 state:{x:1}, mutations: { ... }, actions: { ... }, getters: { bigSum(state){ return state.sum * 10 } } } const personAbout = { namespaced:true,//开启命名空间 state:{ ... }, mutations: { ... }, actions: { ... } } const store = new Vuex.Store({ modules: { countAbout, personAbout } })开启命名空间后,组件中读取state数据:
//方式一:自己直接读取 this.$store.state.personAbout.list //方式二:借助mapState读取: ...mapState('countAbout',['sum','school','subject']),开启命名空间后,组件中读取getters数据:
//方式一:自己直接读取 this.$store.getters['personAbout/firstPersonName'] //方式二:借助mapGetters读取: ...mapGetters('countAbout',['bigSum'])开启命名空间后,组件中调用dispatch
//方式一:自己直接dispatch this.$store.dispatch('personAbout/addPersonWang',person) //方式二:借助mapActions: ...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})开启命名空间后,组件中调用commit
//方式一:自己直接commit this.$store.commit('personAbout/ADD_PERSON',person) //方式二:借助mapMutations: ...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),
29. 求和案例_vuex模板化编码
-
src\store\count.js
// 求和相关配置 export default { namespaced: true, actions: { jiaOdd(context, value){ console.log('actions中的jiaOdd被调用了') if (context.state.sum % 2) { context.commit('JIA', value) } }, jiaWait(context, value){ console.log('actions中的jiaWait被调用了') setTimeout(()=>{ context.commit('JIA', value) }, 1000) }, }, mutations: { JIA(state, value){ console.log('mutations中的JIA被调用了') state.sum += value }, JIAN(state, value){ console.log('mutations中的JIAN被调用了') state.sum -= value }, ADD_PERSON(state, value){ console.log('mutations中的ADD_PERSON被调用了') state.personList.unshift(value) } }, state: { // 当前的和 sum:0, school:'尚硅谷', subject:'前端', }, getters: { bigSum(state){ return state.sum * 10 } } } -
src\store\person.js
// 人员管理相关配置 import axios from 'axios' import { nanoid } from "nanoid"; export default { namespaced: true, actions: { addPersonWang(context, value){ if (value.name.indexOf('王') === 0) { context.commit('ADD_PERSON', value) }else { alert('添加的人必须姓王!') } }, addPersonServer(context){ axios.get('https://api.uixsj.cn/hitokoto/get?type=social').then( response => { context.commit('ADD_PERSON', {id:nanoid(), name:response.data}) }, error => { alert(error.message) } ) } }, mutations: { ADD_PERSON(state, value){ console.log('mutations中的ADD_PERSON被调用了') state.personList.unshift(value) } }, state: { personList:[ {id:'001', name:'张三'} ] }, getters:{ firstPersonName(state){ return state.personList[0].name } } } -
src\store\index.js
// 该文件用于创建Vuex中最为核心的store // 引入Vue import Vue from 'vue' // 应用Vuex插件 import Vuex from 'vuex' // 导入模块化配置 import countOptions from './count' import personOptions from './person' // 使用Vuex插件 Vue.use(Vuex) // 创建并暴露store export default new Vuex.Store({ modules:{ countAbout: countOptions, personAbout: personOptions, } }) -
src\components\Count.vue
<<template> <div> <!-- <h1>当前求和为:{{$store.state.sum}}</h1> --> <!-- <h1>当前求和为:{{he}}</h1> --> <h1>当前求和为:{{sum}}</h1> <!-- <h3>当前求和放大10倍为:{{$store.getters.bigSum}}</h3> --> <h3>当前求和放大10倍为:{{bigSum}}</h3> <!-- <h1>我在{{xuexiao}},学习{{xueke}}</h1> --> <h3>我在{{school}},学习{{subject}}</h3> <h3>Person组件的总人数是:{{personList.length}}</h3> <!-- v-model.number限制value的数据类型为数值 --> <select v-model.number="n"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <!-- mapActions与mapMutations使用时,若需要传递参数需要:在模板中绑定事件时传递好参数,否则参数是事件对象。 --> <button @click="increment(n)">+</button> <button @click="decrement(n)">-</button> <button @click="oddIncrement(n)">当前求和为奇数再加</button> <button @click="waitIncrement(n)">等一等再加</button> </div> </template> <script> // 引入mapState和mapGetters、mapActions和mapMutations import { mapState, mapGetters, mapActions, mapMutations } from "vuex"; export default { name: 'Count', data(){ return { // 用户选择的数字 n:1 } }, computed:{ // 使用mapState生成计算属性,从state中读取数据(当key和value相同时,可以用数组写法) ...mapState('countAbout', ['sum', 'school', 'subject', 'personList']), ...mapState('personAbout', ['personList']), // 使用mapGetters生成计算属性,从getters中读取数据(当key和value相同时,可以用数组写法) ...mapGetters('countAbout', ['bigSum']) }, methods:{ // 使用mapMutations生成对应的方法,方法会调用commit去联系mutations(对象写法) ...mapMutations('countAbout', {increment:'JIA', decrement:'JIAN'}), // 使用mapActions生成对应的方法,方法会调用dispatch去联系actions(对象写法) ...mapActions('countAbout', {oddIncrement:'jiaOdd', waitIncrement:'jiaWait'}), }, }; </script> <style lang="css" scoped> button{ margin-left: 5px; } </style> -
src\components\Person.vue
<<template> <div> <h1>人员列表</h1> <h3 style="color:red">Count组件求和为:{{sum}}</h3> <h3>列表中第一个人的名字是:{{firstPersonName}}</h3> <input type="text" placeholder="请输入名字" v-model="name" @keyup.enter="add"> <button @click="add">添加</button> <button @click="addWang">添加一个姓王的人</button> <button @click="addPersonServer">添加一个人,随机名字</button> <ul> <li v-for="p in personList" :key="p.id">{{p.name}}</li> </ul> </div> </template> <script> import {nanoid} from 'nanoid' export default { name: 'Person', data(){ return { name:'' } }, computed:{ personList(){ return this.$store.state.personAbout.personList }, sum(){ return this.$store.state.countAbout.sum }, firstPersonName(){ return this.$store.getters.firstPersonName } }, methods:{ add(){ const personObj = {id:nanoid(), name:this.name} this.$store.commit('personAbout/ADD_PERSON', personObj) this.name = '' }, addWang(){ const personObj = {id:nanoid(), name:this.name} this.$store.dispatch('personAbout/addPersonWang', personObj) this.name = '' }, addPersonServer(){ const personObj = {id:nanoid(), name:this.name} this.$store.dispatch('personAbout/addPersonServer', personObj) this.name = '' } } }; </script> <style lang="css" scoped> button{ margin-left: 5px; } </style>
路由
1.基本使用
安装vue-router,vue2的版本只能和vue-router 3.x使用,vue-router 4.x和vue3使用,如果安装vue-router不标注版本的话,会默认安装vue-router 4.x的版本。命令:
npm i vue-router@3应用插件:
Vue.use(VueRouter)编写router配置项:
//引入VueRouter import VueRouter from 'vue-router' //引入Luyou 组件 import About from '../components/About' import Home from '../components/Home' //创建router实例对象,去管理一组一组的路由规则 const router = new VueRouter({ routes:[ { path:'/about', component:About }, { path:'/home', component:Home } ] }) //暴露router export default router实现切换(active-class可配置高亮样式)
<router-link active-class="active" to="/about">About</router-link>指定展示位置
<router-view></router-view>
30. 路由的基本使用
-
public\index.html(bootstrap.css样式就是在这里添加)
<!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <!-- 针对IE浏览器的一个特殊配置,含义是让IE浏览器以最高的渲染级别渲染页面 --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- 开启移动端的理想视口 --> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <!-- 配置页签图标 --> <link rel="icon" href="<%= BASE_URL %>favicon.ico"> <!-- 引入第三方样式 --> <link rel="stylesheet" href="<%= BASE_URL %>css/bootstrap.css"> <!-- 配置网页标题 --> <title>硅谷系统</title> </head> <body> <!-- 当浏览器不支持js时noscript中的元素就会被渲染 --> <noscript> <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <!-- 容器 --> <div id="app"></div> <!-- built files will be auto injected --> </body> </html> -
src\router\index.js
// 该文件专门用于创建整个应用的路由器 import VueRouter from 'vue-router' //引入组件 import About from '../components/About' import Home from '../components/Home' //创建并暴露一个路由器 export default new VueRouter({ routes:[ { path:'/about', component:About }, { path:'/home', component:Home } ] }) -
src\main.js
/* 该文件是整个项目的入口文件 */ // 引入Vue import Vue from 'vue' // 引入App组件,它是所有组件的父组件 import App from './App.vue' // 引入VueRouter import VueRouter from 'vue-router' // 引入路由器 import router from './router' // 关闭Vue的生产提示 Vue.config.productionTip = false Vue.use(VueRouter) // 创建Vue实例对象——vm new Vue({ el:'#app', render: h => h(App), router:router }) -
src\components\About.vue
<template> <h2>我是About的内容</h2> </template> <script> export default { name:'About', /* beforeDestroy() { console.log('About组件即将被销毁了') },*/ /* mounted() { console.log('About组件挂载完毕了',this) window.aboutRoute = this.$route window.aboutRouter = this.$router }, */ } </script> <style scoped> </style> -
src\components\Home.vue
<template> <h2>我是Home的内容</h2> </template> <script> export default { name:'Home', /* beforeDestroy() { console.log('Home组件即将被销毁了') }, */ /* mounted() { console.log('Home组件挂载完毕了',this) window.homeRoute = this.$route window.homeRouter = this.$router }, */ } </script> <style scoped> </style> -
src\App.vue
<template> <div> <div class="row"> <div class="col-xs-offset-2 col-xs-8"> <div class="page-header"><h2>Vue Router Demo</h2></div> </div> </div> <div class="row"> <div class="col-xs-2 col-xs-offset-2"> <div class="list-group"> <!-- 原始html中我们使用a标签实现页面的跳转 --> <!-- <a class="list-group-item active" href="./about.html">About</a> <a class="list-group-item" href="./home.html">Home</a><br> --> <!-- Vue中借助router-link标签实现路由的切换 --> <router-link class="list-group-item" active-class="active" to="/about">About</router-link> <router-link class="list-group-item" active-class="active" to="/home">home</router-link> </div> </div> <div class="col-xs-6"> <div class="panel"> <div class="panel-body"> <!-- <h2>我是About的内容</h2> --> <!-- 指定组件的呈现位置 --> <router-view></router-view> </div> </div> </div> </div> </div> </template> <script> export default { name: 'App' }; </script> <style scoped> </style>
2.几个注意点
- 路由组件通常存放在
pages文件夹,一般组件通常存放在components文件夹。- 通过切换,“隐藏”了的路由组件,默认是被销毁掉的,需要的时候再去挂载。
- 每个组件都有自己的
$route属性,里面存储着自己的路由信息。- 整个应用只有一个router,可以通过组件的
$router属性获取到。
3.多级路由(多级路由)
配置路由规则,使用children配置项:
routes:[ { path:'/about', component:About, }, { path:'/home', component:Home, children:[ //通过children配置子级路由 { path:'news', //此处一定不要写:/news component:News }, { path:'message',//此处一定不要写:/message component:Message } ] } ]跳转(要写完整路径):
<router-link to="/home/news">News</router-link>
31. 多级路由
-
src\components\Banner.vue(将标题部分拆分到Banner.vue中)
<template> <div class="col-xs-offset-2 col-xs-8"> <div class="page-header"><h2>Vue Router Demo</h2></div> </div> </template> <script> export default { name:'Banner' } </script> <style scoped> </style> -
src\pages\News.vue
<template> <ul> <li>news001</li> <li>news002</li> <li>news003</li> </ul> </template> <script> export default { name:'News' } </script> <style scoped> </style> -
src\pages\Message.vue
<template> <div> <ul> <li> <a href="/message1">message001</a> </li> <li> <a href="/message2">message002</a> </li> <li> <a href="/message3">message003</a> </li> </ul> </div> </template> <script> export default { name:'Message' } </script> <style scoped> </style> -
src\pages\Home.vue
<template> <div> <h2>我是Home的内容</h2> <div> <ul class="nav nav-tabs"> <li> <router-link class="list-group-item" active-class="active" to="/home/news">News</router-link> </li> <li> <router-link class="list-group-item" active-class="active" to="/home/message">Message</router-link> </li> </ul> <hr> <router-view></router-view> </div> </div> </template> <script> export default { name:'Home' } </script> <style scoped> </style> -
src\router\index.js
// 该文件专门用于创建整个应用的路由器 import VueRouter from 'vue-router' //引入组件 import About from '../pages/About' import Home from '../pages/Home' import News from '../pages/News' import Message from '../pages/Message' //创建并暴露一个路由器 export default new VueRouter({ routes:[ { path:'/about', component:About }, { path:'/home', component:Home, //通过children配置子级路由 children:[ { //此处一定不要写:/news path:'news', component:News }, { //此处一定不要写:/message path:'message', component:Message }, ] } ] })
4.路由的query参数
传递参数
<!-- 跳转并携带query参数,to的字符串写法 --> <router-link :to="/home/message/detail?id=666&title=你好">跳转</router-link> <!-- 跳转并携带query参数,to的对象写法 --> <router-link :to="{ path:'/home/message/detail', query:{ id:666, title:'你好' } }" >跳转</router-link>接收参数:
$route.query.id $route.query.title
32. 路由的query参数
-
src\pages\Detail.vue
<template> <ul> <li>消息编号:{{$route.query.id}}</li> <li>消息标题:{{$route.query.title}}</li> </ul> </template> <script> export default { name:'Detail', mounted(){ console.log(this.$route) } } </script> <style scoped> </style> -
src\pages\Message.vue
<template> <div> <ul> <li v-for="m in messageList" :key="m.id"> <!-- 跳转路由并携带query参数,to的字符串写法 --> <!-- <router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">{{m.title}}</router-link> --> <!-- 跳转路由并携带query参数,to的字符串写法 --> <router-link :to="{ path:'/home/message/detail', query:{ id:m.id, title:m.title } }" >{{m.title}}</router-link> </li> </ul> <hr> <router-view></router-view> </div> </template> <script> export default { name:'Message', data(){ return { messageList:[ {id:'001', title:'消息001'}, {id:'002', title:'消息002'}, {id:'003', title:'消息003'}, ] } } } </script> <style scoped> </style> -
src\router\index.js
// 该文件专门用于创建整个应用的路由器 import VueRouter from 'vue-router' //引入组件 import About from '../pages/About' import Home from '../pages/Home' import News from '../pages/News' import Message from '../pages/Message' import Detail from '../pages/Detail' //创建并暴露一个路由器 export default new VueRouter({ routes:[ { path:'/about', component:About }, { path:'/home', component:Home, //通过children配置子级路由 children:[ { //此处一定不要写:/news path:'news', component:News }, { //此处一定不要写:/message path:'message', component:Message, children:[ { path:'detail', component:Detail }, ] }, ] } ] })
5.命名路由
作用:可以简化路由的跳转。
如何使用
给路由命名:
{ path:'/demo', component:Demo, children:[ { path:'test', component:Test, children:[ { name:'hello', //给路由命名 path:'welcome', component:Hello, } ] } ] }简化跳转:
<!--简化前,需要写完整的路径 --> <router-link to="/demo/test/welcome">跳转</router-link> <!--简化后,直接通过名字跳转 --> <router-link :to="{name:'hello'}">跳转</router-link> <!--简化写法配合传递参数 --> <router-link :to="{ name:'hello', query:{ id:666, title:'你好' } }" >跳转</router-link>
33. 命名路由
-
src\pages\Message.vue
<template> <div> <ul> <li v-for="m in messageList" :key="m.id"> <!-- 跳转路由并携带query参数,to的字符串写法 --> <!-- <router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">{{m.title}}</router-link> --> <!-- 跳转路由并携带query参数,to的字符串写法 --> <router-link :to="{ // path:'/home/message/detail', name:'xiangqing', query:{ id:m.id, title:m.title } }" >{{m.title}}</router-link> </li> </ul> <hr> <router-view></router-view> </div> </template> <script> export default { name:'Message', data(){ return { messageList:[ {id:'001', title:'消息001'}, {id:'002', title:'消息002'}, {id:'003', title:'消息003'}, ] } } } </script> <style scoped> </style> -
src\router\index.js
// 该文件专门用于创建整个应用的路由器 import VueRouter from 'vue-router' //引入组件 import About from '../pages/About' import Home from '../pages/Home' import News from '../pages/News' import Message from '../pages/Message' import Detail from '../pages/Detail' //创建并暴露一个路由器 export default new VueRouter({ routes:[ { name:'guanyu', path:'/about', component:About }, { path:'/home', component:Home, //通过children配置子级路由 children:[ { //此处一定不要写:/news path:'news', component:News }, { //此处一定不要写:/message path:'message', component:Message, children:[ { // 命名路由 name:'xiangqing', path:'detail', component:Detail }, ] }, ] } ] })
6.路由的params参数
配置路由,声明接收params参数
{ path:'/home', component:Home, children:[ { path:'news', component:News }, { component:Message, children:[ { name:'xiangqing', path:'detail/:id/:title', //使用占位符声明接收params参数 component:Detail } ] } ] }传递参数
<!-- 跳转并携带params参数,to的字符串写法 --> <router-link :to="/home/message/detail/666/你好">跳转</router-link> <!-- 跳转并携带params参数,to的对象写法 --> <router-link :to="{ name:'xiangqing', params:{ id:666, title:'你好' } }" >跳转</router-link>特别注意:路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置!
接收参数:
$route.params.id $route.params.title
34. 路由的params参数
-
src\router\index.js
// 该文件专门用于创建整个应用的路由器 import VueRouter from 'vue-router' //引入组件 import About from '../pages/About' import Home from '../pages/Home' import News from '../pages/News' import Message from '../pages/Message' import Detail from '../pages/Detail' //创建并暴露一个路由器 export default new VueRouter({ routes:[ { name:'guanyu', path:'/about', component:About }, { path:'/home', component:Home, //通过children配置子级路由 children:[ { //此处一定不要写:/news path:'news', component:News }, { //此处一定不要写:/message path:'message', component:Message, children:[ { // 命名路由 name:'xiangqing', // 使用占位符声明接收params参数 path:'detail/:id/:title', component:Detail }, ] }, ] } ] }) -
src\pages\Message.vue
<template> <div> <ul> <li v-for="m in messageList" :key="m.id"> <!-- 跳转路由并携带query参数,to的字符串写法 --> <!-- <router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">{{m.title}}</router-link> --> <!-- 跳转路由并携带query参数,to的字符串写法 --> <!-- <router-link :to="{ // path:'/home/message/detail', name:'xiangqing', query:{ id:m.id, title:m.title } }" >{{m.title}}</router-link> --> <!-- 跳转路由并携带params参数,to的字符串写法 --> <!-- <router-link :to="`/home/message/detail/${m.id}/${m.title}`">{{m.title}}</router-link> --> <!-- 跳转路由并携带params参数,to的字符串写法 --> <!-- 路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置! --> <router-link :to="{ // path:'/home/message/detail', name:'xiangqing', params:{ id:m.id, title:m.title } }" >{{m.title}}</router-link> </li> </ul> <hr> <router-view></router-view> </div> </template> <script> export default { name:'Message', data(){ return { messageList:[ {id:'001', title:'消息001'}, {id:'002', title:'消息002'}, {id:'003', title:'消息003'}, ] } } } </script> <style scoped> </style> -
src\pages\Detail.vue
<template> <ul> <!-- <li>消息编号:{{$route.query.id}}</li> <li>消息标题:{{$route.query.title}}</li> --> <li>消息编号:{{$route.params.id}}</li> <li>消息标题:{{$route.params.title}}</li> </ul> </template> <script> export default { name:'Detail', mounted(){ console.log(this.$route) } } </script> <style scoped> </style>
7.路由的props配置
作用:让路由组件更方便的收到参数
{ name:'xiangqing', path:'detail/:id', component:Detail, //第一种写法:props值为对象,该对象中所有的key-value的组合最终都会通过props传给Detail组件 // props:{a:900} //第二种写法:props值为布尔值,布尔值为true,则把路由收到的所有params参数通过props传给Detail组件 // props:true //第三种写法:props值为函数,该函数返回的对象中每一组key-value都会通过props传给Detail组件 props($route){ return { id:$route.query.id, title:$route.query.title } } }
35. 路由的props配置
-
src\router\index.js
// 该文件专门用于创建整个应用的路由器 import VueRouter from 'vue-router' //引入组件 import About from '../pages/About' import Home from '../pages/Home' import News from '../pages/News' import Message from '../pages/Message' import Detail from '../pages/Detail' //创建并暴露一个路由器 export default new VueRouter({ routes:[ { name:'guanyu', path:'/about', component:About }, { path:'/home', component:Home, //通过children配置子级路由 children:[ { //此处一定不要写:/news path:'news', component:News }, { //此处一定不要写:/message path:'message', component:Message, children:[ { // 命名路由 name:'xiangqing', path:'detail', // 使用占位符声明接收params参数 // path:'detail/:id/:title', component:Detail, // props的第一种写法,值为对象,该对象中的所有key-value都会以props的形式传给Detail组件 // props:{a:1, b:'hello'} // props的第二种写法,值为布尔值,若布尔值为真,就会把该路由组件收到的所有params参数(path记得使用占位符声明接收params参数),以props的形式传给Detail组件 // props:true // props的第三种写法,值为函数 props($route){ return { id:$route.query.id, title:$route.query.title, a:1, b:'hello' } } }, ] }, ] } ] }) -
src\pages\Message.vue
<template> <div> <ul> <li v-for="m in messageList" :key="m.id"> <!-- 跳转路由并携带query参数,to的字符串写法 --> <!-- <router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">{{m.title}}</router-link> --> <!-- 跳转路由并携带query参数,to的字符串写法 --> <router-link :to="{ // path:'/home/message/detail', name:'xiangqing', query:{ id:m.id, title:m.title } }" >{{m.title}}</router-link> <!-- 跳转路由并携带params参数,to的字符串写法 --> <!-- <router-link :to="`/home/message/detail/${m.id}/${m.title}`">{{m.title}}</router-link> --> <!-- 跳转路由并携带params参数,to的字符串写法 --> <!-- 路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置! --> <!-- <router-link :to="{ // path:'/home/message/detail', name:'xiangqing', params:{ id:m.id, title:m.title, } }" >{{m.title}}</router-link> --> </li> </ul> <hr> <router-view></router-view> </div> </template> <script> export default { name:'Message', data(){ return { messageList:[ {id:'001', title:'消息001'}, {id:'002', title:'消息002'}, {id:'003', title:'消息003'}, ] } } } </script> <style scoped> </style> -
src\pages\Detail.vue
<template> <ul> <li>消息编号:{{id}}</li> <li>消息标题:{{title}}</li> <!-- <li>消息编号:{{$route.params.id}}</li> <li>消息标题:{{$route.params.title}}</li> --> <li>{{a}}</li> <li>{{b}}</li> </ul> </template> <script> export default { name:'Detail', props:['a', 'b', 'id', 'title'], // computed:{ // id(){ // return this.$route.query.id // }, // title(){ // return this.$route.query.title // }, // }, mounted(){ console.log(this.$route) } } </script> <style scoped> </style>
8.<router-link>的replace属性
- 作用:控制路由跳转时操作浏览器历史记录的模式
- 浏览器的历史记录有两种写入方式:分别为
push和replace,push是追加历史记录,replace是替换当前记录。路由跳转时候默认为push- 如何开启
replace模式:<router-link replace .......>News</router-link>
36. <router-link>的replace属性
-
src\pages\Home.vue
<template> <div> <h2>我是Home的内容</h2> <div> <ul class="nav nav-tabs"> <li> <!-- push是追加历史记录,即增加记录,仍然可以返回上一跳浏览记录 --> <!-- replace是替换当前记录,即覆盖上一跳浏览记录,不能返回上一跳浏览记录 --> <router-link replace class="list-group-item" active-class="active" to="/home/news">News</router-link> </li> <li> <router-link replace class="list-group-item" active-class="active" to="/home/message">Message</router-link> </li> </ul> <hr> <router-view></router-view> </div> </div> </template> <script> export default { name:'Home' } </script> <style scoped> </style>
9.编程式路由导航
作用:不借助
<router-link>实现路由跳转,让路由跳转更加灵活具体编码:
//$router的两个API this.$router.push({ name:'xiangqing', params:{ id:xxx, title:xxx } }) this.$router.replace({ name:'xiangqing', params:{ id:xxx, title:xxx } }) this.$router.forward() //前进 this.$router.back() //后退 this.$router.go() //可前进也可后退
37. 编程式路由导航
-
src\components\Banner.vue
<template> <div class="col-xs-offset-2 col-xs-8"> <div class="page-header"> <h2>Vue Router Demo</h2> <button @click="back">后退</button> <button @click="forward">前进</button> <button @click="go">测试go</button> </div> </div> </template> <script> export default { name:'Banner', methods:{ back(){ // console.log(this.$router) this.$router.back() }, forward(){ this.$router.forward() }, go(){ this.$router.go(3) } } } </script> <style scoped> </style> -
src\pages\Message.vue
<template> <div> <ul> <li v-for="m in messageList" :key="m.id"> <!-- 跳转路由并携带query参数,to的字符串写法 --> <!-- <router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">{{m.title}}</router-link> --> <!-- 跳转路由并携带query参数,to的字符串写法 --> <router-link :to="{ name:'xiangqing', query:{ id:m.id, title:m.title } }" >{{m.title}}</router-link> <button @click="pushShow(m)">push查看</button> <button @click="replaceShow(m)">replace查看</button> </li> </ul> <hr> <router-view></router-view> </div> </template> <script> export default { name:'Message', data(){ return { messageList:[ {id:'001', title:'消息001'}, {id:'002', title:'消息002'}, {id:'003', title:'消息003'}, ] } }, methods:{ pushShow(m){ this.$router.push({ name:'xiangqing', query:{ id:m.id, title:m.title } }) }, replaceShow(m){ this.$router.replace({ name:'xiangqing', query:{ id:m.id, title:m.title } }) }, } } </script> <style scoped> </style>
10.缓存路由组件
作用:让不展示的路由组件保持挂载,不被销毁。
具体编码:
<keep-alive include="News"> <router-view></router-view> </keep-alive>
38. 缓存路由组件
-
src\pages\News.vue
<template> <ul> <li>news001</li> <li>news002</li> <li>news003</li> </ul> </template> <script> export default { name:'News', beforeDestroy() { console.log('News组件即将被销毁了') }, } </script> <style scoped> </style> -
src\pages\Message.vue
<template> <div> <ul> <li v-for="m in messageList" :key="m.id"> <!-- 跳转路由并携带query参数,to的字符串写法 --> <!-- <router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">{{m.title}}</router-link> --> <!-- 跳转路由并携带query参数,to的字符串写法 --> <router-link :to="{ name:'xiangqing', query:{ id:m.id, title:m.title } }" >{{m.title}}</router-link> <button @click="pushShow(m)">push查看</button> <button @click="replaceShow(m)">replace查看</button> </li> </ul> <hr> <router-view></router-view> </div> </template> <script> export default { name:'Message', data(){ return { messageList:[ {id:'001', title:'消息001'}, {id:'002', title:'消息002'}, {id:'003', title:'消息003'}, ] } }, methods:{ pushShow(m){ this.$router.push({ name:'xiangqing', query:{ id:m.id, title:m.title } }) }, replaceShow(m){ this.$router.replace({ name:'xiangqing', query:{ id:m.id, title:m.title } }) }, }, beforeDestroy() { console.log('Message组件即将被销毁了') }, } </script> <style scoped> </style> -
src\pages\Home.vue
<template> <div> <h2>我是Home的内容</h2> <div> <ul class="nav nav-tabs"> <li> <router-link class="list-group-item" active-class="active" to="/home/news">News</router-link> </li> <li> <router-link class="list-group-item" active-class="active" to="/home/message">Message</router-link> </li> </ul> <hr> <!-- <router-view></router-view> --> <!-- 缓存一个路由组件 include内的是组件名称 --> <keep-alive include="News"> <router-view></router-view> </keep-alive> <!-- 缓存多个路由组件 --> <!-- <keep-alive :include="['News','Message']"> <router-view></router-view> </keep-alive> --> </div> </div> </template> <script> export default { name:'Home' } </script> <style scoped> </style>
11.两个新的生命周期钩子
- 作用:路由组件所独有的两个钩子,用于捕获路由组件的激活状态。
- 具体名字:
activated路由组件被激活时触发。deactivated路由组件失活时触发。
39. 两个新的生命周期钩子
-
src\pages\News.vue
<template> <ul> <li :style="{opacity}">欢迎学习Vue</li> <li>news001</li> <li>news002</li> <li>news003</li> </ul> </template> <script> export default { name:'News', data(){ return { opacity:1 } }, // beforeDestroy() { // console.log('News组件即将被销毁了') // }, activated(){ console.log('News组件被激活了') this.timer = setInterval(()=>{ console.log('@') this.opacity -= 0.01 if (this.opacity < 0) { this.opacity = 1 } }, 16) }, deactivated(){ console.log('News组件失活了') clearInterval(this.timer) } } </script> <style scoped> </style>
12.路由守卫
作用:对路由进行权限控制
分类:全局守卫、独享守卫、组件内守卫
全局守卫:
//全局前置守卫:初始化时执行、每次路由切换前执行 router.beforeEach((to,from,next)=>{ console.log('beforeEach',to,from) if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制 if(localStorage.getItem('school') === 'atguigu'){ //权限控制的具体规则 next() //放行 }else{ alert('暂无权限查看') // next({name:'guanyu'}) } }else{ next() //放行 } }) //全局后置守卫:初始化时执行、每次路由切换后执行 router.afterEach((to,from)=>{ console.log('afterEach',to,from) if(to.meta.title){ document.title = to.meta.title //修改网页的title }else{ document.title = 'vue_test' } })独享守卫:(在一个路由内部单独写一个守卫)
beforeEnter(to,from,next){ console.log('beforeEnter',to,from) if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制 if(localStorage.getItem('school') === 'atguigu'){ next() }else{ alert('暂无权限查看') // next({name:'guanyu'}) } }else{ next() } }组件内守卫:
//进入守卫:通过路由规则,进入该组件时被调用 beforeRouteEnter (to, from, next) { }, //离开守卫:通过路由规则,离开该组件时被调用 beforeRouteLeave (to, from, next) { }
40. 全局路由守卫
-
src\router\index.js
// 该文件专门用于创建整个应用的路由器 import VueRouter from 'vue-router' //引入组件 import About from '../pages/About' import Home from '../pages/Home' import News from '../pages/News' import Message from '../pages/Message' import Detail from '../pages/Detail' //创建并暴露一个路由器 const router = new VueRouter({ routes:[ { name:'guanyu', path:'/about', component:About, meta:{title:'关于'} }, { name:'zhuye', path:'/home', component:Home, meta:{title:'主页'}, //通过children配置子级路由 children:[ { //此处一定不要写:/news name:'xinwen', path:'news', component:News, meta:{isAuth:true, title:'新闻'} }, { //此处一定不要写:/message path:'message', component:Message, meta:{isAuth:true, title:'消息'}, children:[ { // 命名路由 name:'xiangqing', path:'detail', // 使用占位符声明接收params参数 // path:'detail/:id/:title', component:Detail, meta:{isAuth:true, title:'详情'}, // props的第一种写法,值为对象,该对象中的所有key-value都会以props的形式传给Detail组件 // props:{a:1, b:'hello'} // props的第二种写法,值为布尔值,若布尔值为真,就会把该路由组件收到的所有params参数(path记得使用占位符声明接收params参数),以props的形式传给Detail组件 // props:true // props的第三种写法,值为函数 props($route){ return { id:$route.query.id, title:$route.query.title, a:1, b:'hello' } } }, ] }, ] } ] }) // 全局前置路由守卫————初始化的时候被调用,每次路由切换之前被调用 router.beforeEach((to, from, next)=>{ console.log('前置路由守卫',to,from) // 判断是否需要鉴权 if (to.meta.isAuth) { if (localStorage.getItem('school') === 'atguigu') { next() }else { alert('学校名不对,无权限查看!') } }else { next() } }) // 全局后置路由守卫————初始化的时候被调用,每次切换路由后被调用 router.afterEach((to, from)=>{ console.log('后置路由守卫',to,from) document.title = to.meta.title || '硅谷系统' }) export default router
41. 独享路由守卫
-
src\router\index.js
// 该文件专门用于创建整个应用的路由器 import VueRouter from 'vue-router' //引入组件 import About from '../pages/About' import Home from '../pages/Home' import News from '../pages/News' import Message from '../pages/Message' import Detail from '../pages/Detail' //创建并暴露一个路由器 const router = new VueRouter({ routes:[ { name:'guanyu', path:'/about', component:About, meta:{title:'关于'} }, { name:'zhuye', path:'/home', component:Home, meta:{title:'主页'}, children:[ { name:'xinwen', path:'news', component:News, meta:{isAuth:true,title:'新闻'}, beforeEnter: (to, from, next) => { console.log('独享路由守卫',to,from) if(to.meta.isAuth){ //判断是否需要鉴权 if(localStorage.getItem('school')==='atguigu'){ next() }else{ alert('学校名不对,无权限查看!') } }else{ next() } } }, { name:'xiaoxi', path:'message', component:Message, meta:{isAuth:true,title:'消息'}, children:[ { name:'xiangqing', path:'detail', component:Detail, meta:{isAuth:true,title:'详情'}, //props的第一种写法,值为对象,该对象中的所有key-value都会以props的形式传给Detail组件。 // props:{a:1,b:'hello'} //props的第二种写法,值为布尔值,若布尔值为真,就会把该路由组件收到的所有params参数,以props的形式传给Detail组件。 // props:true //props的第三种写法,值为函数 props($route){ return { id:$route.query.id, title:$route.query.title, a:1, b:'hello' } } } ] } ] } ] }) //全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用 /* router.beforeEach((to,from,next)=>{ console.log('前置路由守卫',to,from) if(to.meta.isAuth){ //判断是否需要鉴权 if(localStorage.getItem('school')==='atguigu'){ next() }else{ alert('学校名不对,无权限查看!') } }else{ next() } }) */ //全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用 router.afterEach((to,from)=>{ console.log('后置路由守卫',to,from) document.title = to.meta.title || '硅谷系统' }) export default router
42. 组件内路由守卫
-
src\router\index.js
// 该文件专门用于创建整个应用的路由器 import VueRouter from 'vue-router' //引入组件 import About from '../pages/About' import Home from '../pages/Home' import News from '../pages/News' import Message from '../pages/Message' import Detail from '../pages/Detail' //创建并暴露一个路由器 const router = new VueRouter({ routes:[ { name:'guanyu', path:'/about', component:About, meta:{isAuth:true, title:'关于'} }, { name:'zhuye', path:'/home', component:Home, meta:{title:'主页'}, //通过children配置子级路由 children:[ { //此处一定不要写:/news name:'xinwen', path:'news', component:News, meta:{isAuth:true, title:'新闻'}, // 独享路由守卫 beforeEnter:(to, from, next)=>{ console.log('独享路由守卫',to,from) // 判断是否需要鉴权 if (to.meta.isAuth) { if (localStorage.getItem('school') === 'atguigu') { next() }else { alert('学校名不对,无权限查看!') } }else { next() } } }, { //此处一定不要写:/message path:'message', component:Message, meta:{isAuth:true, title:'消息'}, children:[ { // 命名路由 name:'xiangqing', path:'detail', // 使用占位符声明接收params参数 // path:'detail/:id/:title', component:Detail, meta:{isAuth:true, title:'详情'}, // props的第一种写法,值为对象,该对象中的所有key-value都会以props的形式传给Detail组件 // props:{a:1, b:'hello'} // props的第二种写法,值为布尔值,若布尔值为真,就会把该路由组件收到的所有params参数(path记得使用占位符声明接收params参数),以props的形式传给Detail组件 // props:true // props的第三种写法,值为函数 props($route){ return { id:$route.query.id, title:$route.query.title, a:1, b:'hello' } } }, ] }, ] } ] }) // 全局前置路由守卫————初始化的时候被调用,每次路由切换之前被调用 // router.beforeEach((to, from, next)=>{ // console.log('前置路由守卫',to,from) // // 判断是否需要鉴权 // if (to.meta.isAuth) { // if (localStorage.getItem('school') === 'atguigu') { // next() // }else { // alert('学校名不对,无权限查看!') // } // }else { // next() // } // }) // 全局后置路由守卫————初始化的时候被调用,每次切换路由后被调用 router.afterEach((to, from)=>{ console.log('后置路由守卫',to,from) document.title = to.meta.title || '硅谷系统' }) export default router -
src\pages\About.vue
<template> <h2>我是About的内容</h2> </template> <script> export default { name:'About', // 通过路由规则,进入该组件时被调用 beforeRouteEnter(to, from, next){ console.log('About--beforeRouteEnter',to,from) // 判断是否需要鉴权 if (to.meta.isAuth) { if (localStorage.getItem('school') === 'atguigu') { next() }else { alert('学校名不对,无权限查看!') } }else { next() } }, // 通过路由规则,离开该组件时被调用 beforeRouteLeave(to, from, next){ console.log('About--beforeRouteLeave',to,from) next() } } </script> <style scoped> </style>
13.路由器的两种工作模式
- 对于一个url来说,什么是hash值?—— #及其后面的内容就是hash值。
- hash值不会包含在 HTTP 请求中,即:hash值不会带给服务器。
- hash模式:
- 地址中永远带着#号,不美观 。
- 若以后将地址通过第三方手机app分享,若app校验严格,则地址会被标记为不合法。
- 兼容性较好。
- history模式:
- 地址干净,美观 。
- 兼容性和hash模式相比略差。
- 应用部署上线时需要后端人员支持,解决刷新页面服务端404的问题。
43. history模式与hash模式
-
src\router\index.js
// 该文件专门用于创建整个应用的路由器 import VueRouter from 'vue-router' //引入组件 import About from '../pages/About' import Home from '../pages/Home' import News from '../pages/News' import Message from '../pages/Message' import Detail from '../pages/Detail' //创建并暴露一个路由器 const router = new VueRouter({ // 默认为hash模式,修改为history模式 mode:'history', routes:[ { name:'guanyu', path:'/about', component:About, meta:{isAuth:true, title:'关于'} }, { name:'zhuye', path:'/home', component:Home, meta:{title:'主页'}, //通过children配置子级路由 children:[ { //此处一定不要写:/news name:'xinwen', path:'news', component:News, meta:{isAuth:true, title:'新闻'}, // 独享路由守卫 beforeEnter:(to, from, next)=>{ console.log('独享路由守卫',to,from) // 判断是否需要鉴权 if (to.meta.isAuth) { if (localStorage.getItem('school') === 'atguigu') { next() }else { alert('学校名不对,无权限查看!') } }else { next() } } }, { //此处一定不要写:/message path:'message', component:Message, meta:{isAuth:true, title:'消息'}, children:[ { // 命名路由 name:'xiangqing', path:'detail', // 使用占位符声明接收params参数 // path:'detail/:id/:title', component:Detail, meta:{isAuth:true, title:'详情'}, // props的第一种写法,值为对象,该对象中的所有key-value都会以props的形式传给Detail组件 // props:{a:1, b:'hello'} // props的第二种写法,值为布尔值,若布尔值为真,就会把该路由组件收到的所有params参数(path记得使用占位符声明接收params参数),以props的形式传给Detail组件 // props:true // props的第三种写法,值为函数 props($route){ return { id:$route.query.id, title:$route.query.title, a:1, b:'hello' } } }, ] }, ] } ] }) // 全局前置路由守卫————初始化的时候被调用,每次路由切换之前被调用 // router.beforeEach((to, from, next)=>{ // console.log('前置路由守卫',to,from) // // 判断是否需要鉴权 // if (to.meta.isAuth) { // if (localStorage.getItem('school') === 'atguigu') { // next() // }else { // alert('学校名不对,无权限查看!') // } // }else { // next() // } // }) // 全局后置路由守卫————初始化的时候被调用,每次切换路由后被调用 router.afterEach((to, from)=>{ console.log('后置路由守卫',to,from) document.title = to.meta.title || '硅谷系统' }) export default router
44. element-ui组件库
完整引入
-
安装组件
npm i element-ui -S -
src\main.js
/* 该文件是整个项目的入口文件 */ // 引入Vue import Vue from 'vue' // 引入App组件,它是所有组件的父组件 import App from './App.vue' // 完整引入 // 引入ElementUI组件库 import ElementUI from 'element-ui' // 引入ElementUI全部样式 import 'element-ui/lib/theme-chalk/index.css' // 关闭Vue的生产提示 Vue.config.productionTip = false // 应用ElementUI Vue.use(ElementUI) // 创建Vue实例对象——vm new Vue({ el:'#app', render: h => h(App), }) -
src\App.vue
<template> <div> <button>原生的按钮</button> <input type="text"> <el-row> <el-button>默认按钮</el-button> <el-button type="primary">主要按钮</el-button> <el-button type="success">成功按钮</el-button> <el-button type="info">信息按钮</el-button> <el-button type="warning">警告按钮</el-button> <el-button type="danger">危险按钮</el-button> </el-row> <el-date-picker type="date" placeholder="选择日期"> </el-date-picker> <el-row> <el-button icon="el-icon-search" circle></el-button> <el-button type="primary" icon="el-icon-edit" circle></el-button> <el-button type="success" icon="el-icon-check" circle></el-button> <el-button type="info" icon="el-icon-message" circle></el-button> <el-button type="warning" icon="el-icon-star-off" circle></el-button> <el-button type="danger" icon="el-icon-delete" circle></el-button> </el-row> </div> </template> <script> export default { name: 'App', }; </script> <style scoped> </style>
按需引入
-
安装组件
npm install babel-plugin-component -D -
修改文件babel.config.js为
module.exports = { presets: [ '@vue/cli-plugin-babel/preset', ["@babel/preset-env", { "modules": false }] ], "plugins": [ [ "component", { "libraryName": "element-ui", "styleLibraryName": "theme-chalk" } ] ] } -
src\main.js
/* 该文件是整个项目的入口文件 */ // 引入Vue import Vue from 'vue' // 引入App组件,它是所有组件的父组件 import App from './App.vue' // 完整引入 // 引入ElementUI组件库 // import ElementUI from 'element-ui' // 引入ElementUI全部样式 // import 'element-ui/lib/theme-chalk/index.css' // 按需引入 import { Button, Row, DatePicker } from 'element-ui'; // 关闭Vue的生产提示 Vue.config.productionTip = false // 应用ElementUI // Vue.use(ElementUI) Vue.component('atguigu-button', Button) Vue.component('atguigu-row', Row) Vue.component('atguigu-date-picker', DatePicker) // 创建Vue实例对象——vm new Vue({ el:'#app', render: h => h(App), }) -
src\App.vue
<template> <div> <button>原生的按钮</button> <input type="text"> <atguigu-row> <atguigu-button>默认按钮</atguigu-button> <atguigu-button type="primary">主要按钮</atguigu-button> <atguigu-button type="success">成功按钮</atguigu-button> <atguigu-button type="info">信息按钮</atguigu-button> <atguigu-button type="warning">警告按钮</atguigu-button> <atguigu-button type="danger">危险按钮</atguigu-button> </atguigu-row> <atguigu-date-picker type="date" placeholder="选择日期"> </atguigu-date-picker> <atguigu-row> <atguigu-button icon="el-icon-search" circle></atguigu-button> <atguigu-button type="primary" icon="el-icon-edit" circle></atguigu-button> <atguigu-button type="success" icon="el-icon-check" circle></atguigu-button> <atguigu-button type="info" icon="el-icon-message" circle></atguigu-button> <atguigu-button type="warning" icon="el-icon-star-off" circle></atguigu-button> <atguigu-button type="danger" icon="el-icon-delete" circle></atguigu-button> </atguigu-row> </div> </template> <script> export default { name: 'App', }; </script> <style scoped> </style>
文章深入浅出地介绍了Vue.js开发的关键技术点,包括脚手架安装与配置、核心属性如ref与props的应用、mixin与插件的集成、样式管理及TodoList案例实践。同时,探讨了Vue的状态管理工具Vuex的使用、路由配置及浏览器本地存储等进阶知识,适合Vue开发者参考。


443

被折叠的 条评论
为什么被折叠?



