入门(三)"/>
Vue学习入门(三)
Vue学习入门(三)
1. 组件化编程
1.1 组件的定义
实现应用中局部功能代码和资源的集合
1.2 概述
在前端开发过程中,经常出现同样的功能,可以将相同的功能进行抽取,封装为组件
组件(Component)是 Vue.js 最强大的功能之一,组件可以扩展 HTML 元素,封装可重用的代码
组件系统让我们可以用独立可复用的小组件来构建大型应用,几乎任意类型的应用的界面都可以抽象为一个组件树
1.3 图解
1.4 非单文件组件
一个文件包括n个组件
特点:
- 模板编写没有提示
- 没有构建过程, 无法将 ES6 转换成 ES5
- 不支持组件的 CSS
- 真正开发中几乎不用
1.4.1 基本使用
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>基本使用</title><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- Vue中使用组件的三大步骤:一、定义组件(创建组件)二、注册组件三、使用组件(写组件标签)一、如何定义一个组件?使用Vue.extend(options)创建,其中options和new Vue(options)时传入的那个options几乎一样,但也有点区别;区别如下:1.el不要写,为什么? ——— 最终所有的组件都要经过一个vm的管理,由vm中的el决定服务哪个容器。2.data必须写成函数,为什么? ———— 避免组件被复用时,数据存在引用关系。备注:使用template可以配置组件结构。二、如何注册组件?1.局部注册:靠new Vue的时候传入components选项2.全局注册:靠Vueponent('组件名',组件)三、编写组件标签:<school></school>--><!-- 准备好一个容器--><div id="root"><hello></hello><hr><h1>{{msg}}</h1><hr><!-- 第三步:编写组件标签 --><school></school><hr><!-- 第三步:编写组件标签 --><student></student></div><div id="root2"><hello></hello></div></body><script type="text/javascript">Vue.config.productionTip = false//第一步:创建school组件const school = Vue.extend({template:`<div class="demo"><h2>学校名称:{{schoolName}}</h2><h2>学校地址:{{address}}</h2><button @click="showName">点我提示学校名</button> </div>`,// el:'#root', //组件定义时,一定不要写el配置项,因为最终所有的组件都要被一个vm管理,由vm决定服务于哪个容器。data(){return {schoolName:'尚硅谷',address:'北京昌平'}},methods: {showName(){alert(this.schoolName)}},})//第一步:创建student组件const student = Vue.extend({template:`<div><h2>学生姓名:{{studentName}}</h2><h2>学生年龄:{{age}}</h2></div>`,data(){return {studentName:'张三',age:18}}})//第一步:创建hello组件const hello = Vue.extend({template:`<div> <h2>你好啊!{{name}}</h2></div>`,data(){return {name:'Tom'}}})//第二步:全局注册组件Vueponent('hello',hello)//创建vmnew Vue({el:'#root',data:{msg:'你好啊!'},//第二步:注册组件(局部注册)components:{school,student}})new Vue({el:'#root2',})</script>
</html>
1.4.2 几个基本点
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>几个注意点</title><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 几个注意点:1.关于组件名:一个单词组成:第一种写法(首字母小写):school第二种写法(首字母大写):School多个单词组成:第一种写法(kebab-case命名):my-school第二种写法(CamelCase命名):MySchool (需要Vue脚手架支持)备注:(1).组件名尽可能回避HTML中已有的元素名称,例如:h2、H2都不行。(2).可以使用name配置项指定组件在开发者工具中呈现的名字。2.关于组件标签:第一种写法:<school></school>第二种写法:<school/>备注:不用使用脚手架时,<school/>会导致后续组件不能渲染。3.一个简写方式:const school = Vue.extend(options) 可简写为:const school = options--><!-- 准备好一个容器--><div id="root"><h1>{{msg}}</h1><school></school></div></body><script type="text/javascript">Vue.config.productionTip = false//定义组件const s = Vue.extend({name:'atguigu',template:`<div><h2>学校名称:{{name}}</h2> <h2>学校地址:{{address}}</h2> </div>`,data(){return {name:'尚硅谷',address:'北京'}}})new Vue({el:'#root',data:{msg:'欢迎学习Vue!'},components:{school:s}})</script>
</html>
1.4.3 组件的嵌套
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>组件的嵌套</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。//定义student组件const student = Vue.extend({name:'student',template:`<div><h2>学生姓名:{{name}}</h2> <h2>学生年龄:{{age}}</h2> </div>`,data(){return {name:'尚硅谷',age:18}}})//定义school组件const school = Vue.extend({name:'school',template:`<div><h2>学校名称:{{name}}</h2> <h2>学校地址:{{address}}</h2> <student></student></div>`,data(){return {name:'尚硅谷',address:'北京'}},//注册组件(局部)components:{student}})//定义hello组件const hello = Vue.extend({template:`<h1>{{msg}}</h1>`,data(){return {msg:'欢迎来到尚硅谷学习!'}}})//定义app组件const app = Vue.extend({template:`<div> <hello></hello><school></school></div>`,components:{school,hello}})//创建vmnew Vue({template:'<app></app>',el:'#root',//注册组件(局部)components:{app}})</script>
</html>
1.4.4 VueComponent
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>VueComponent</title><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 关于VueComponent:1.school组件本质是一个名为VueComponent的构造函数,且不是程序员定义的,是Vue.extend生成的。2.我们只需要写<school/>或<school></school>,Vue解析时会帮我们创建school组件的实例对象,即Vue帮我们执行的:new VueComponent(options)。3.特别注意:每次调用Vue.extend,返回的都是一个全新的VueComponent!!!!4.关于this指向:(1).组件配置中:data函数、methods中的函数、watch中的函数、computed中的函数 它们的this均是【VueComponent实例对象】。(2).new Vue(options)配置中:data函数、methods中的函数、watch中的函数、computed中的函数 它们的this均是【Vue实例对象】。5.VueComponent的实例对象,以后简称vc(也可称之为:组件实例对象)。Vue的实例对象,以后简称vm。--><!-- 准备好一个容器--><div id="root"><school></school><hello></hello></div></body><script type="text/javascript">Vue.config.productionTip = false//定义school组件const school = Vue.extend({name:'school',template:`<div><h2>学校名称:{{name}}</h2> <h2>学校地址:{{address}}</h2> <button @click="showName">点我提示学校名</button></div>`,data(){return {name:'尚硅谷',address:'北京'}},methods: {showName(){console.log('showName',this)}},})const test = Vue.extend({template:`<span>atguigu</span>`})//定义hello组件const hello = Vue.extend({template:`<div><h2>{{msg}}</h2><test></test> </div>`,data(){return {msg:'你好啊!'}},components:{test}})// console.log('@',school)// console.log('#',hello)//创建vmconst vm = new Vue({el:'#root',components:{school,hello}})</script>
</html>
1.4.5 一个重要的内置关系
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>一个重要的内置关系</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 1.一个重要的内置关系:VueComponent.prototype.__proto__ === Vue.prototype2.为什么要有这个关系:让组件实例对象(vc)可以访问到 Vue原型上的属性、方法。--><!-- 准备好一个容器--><div id="root"><school></school></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。Vue.prototype.x = 99//定义school组件const school = Vue.extend({name:'school',template:`<div><h2>学校名称:{{name}}</h2> <h2>学校地址:{{address}}</h2> <button @click="showX">点我输出x</button></div>`,data(){return {name:'尚硅谷',address:'北京'}},methods: {showX(){console.log(this.x)}},})//创建一个vmconst vm = new Vue({el:'#root',data:{msg:'你好'},components:{school}})//定义一个构造函数/* function Demo(){this.a = 1this.b = 2}//创建一个Demo的实例对象const d = new Demo()console.log(Demo.prototype) //显示原型属性console.log(d.__proto__) //隐式原型属性console.log(Demo.prototype === d.__proto__)//程序员通过显示原型属性操作原型对象,追加一个x属性,值为99Demo.prototype.x = 99console.log('@',d) */</script>
</html>
1.5 单文件组件
一个文件只包括1个组件
2.Vue实例生命周期
图解:
2.1 引出生命周期
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>引出生命周期</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 生命周期:1.又名:生命周期回调函数、生命周期函数、生命周期钩子。2.是什么:Vue在关键时刻帮我们调用的一些特殊名称的函数。3.生命周期函数的名字不可更改,但函数的具体内容是程序员根据需求编写的。4.生命周期函数中的this指向是vm 或 组件实例对象。--><!-- 准备好一个容器--><div id="root"><h2 v-if="a">你好啊</h2><h2 :style="{opacity}">欢迎学习Vue</h2></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',data:{a:false,opacity:1},methods: {},//Vue完成模板的解析并把初始的真实DOM元素放入页面后(挂载完毕)调用mountedmounted(){console.log('mounted',this)setInterval(() => {this.opacity -= 0.01if(this.opacity <= 0) this.opacity = 1},16)},})//通过外部的定时器实现(不推荐)/* setInterval(() => {vm.opacity -= 0.01if(vm.opacity <= 0) vm.opacity = 1},16) */</script>
</html>
2.2 分析声明周期
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>分析生命周期</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root" :x="n"><h2 v-text="n"></h2><h2>当前的n值是:{{n}}</h2><button @click="add">点我n+1</button><button @click="bye">点我销毁vm</button></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',// template:`// <div>// <h2>当前的n值是:{{n}}</h2>// <button @click="add">点我n+1</button>// </div>// `,data:{n:1},methods: {add(){console.log('add')this.n++},bye(){console.log('bye')this.$destroy()}},watch:{n(){console.log('n变了')}},beforeCreate() {console.log('beforeCreate')},created() {console.log('created')},beforeMount() {console.log('beforeMount')},mounted() {console.log('mounted')},beforeUpdate() {console.log('beforeUpdate')},updated() {console.log('updated')},beforeDestroy() {console.log('beforeDestroy')},destroyed() {console.log('destroyed')},})</script>
</html>
2.3 总结生命周期
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>引出生命周期</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 常用的生命周期钩子:1.mounted: 发送ajax请求、启动定时器、绑定自定义事件、订阅消息等【初始化操作】。2.beforeDestroy: 清除定时器、解绑自定义事件、取消订阅消息等【收尾工作】。关于销毁Vue实例1.销毁后借助Vue开发者工具看不到任何信息。2.销毁后自定义事件会失效,但原生DOM事件依然有效。3.一般不会在beforeDestroy操作数据,因为即便操作数据,也不会再触发更新流程了。--><!-- 准备好一个容器--><div id="root"><h2 :style="{opacity}">欢迎学习Vue</h2><button @click="opacity = 1">透明度设置为1</button><button @click="stop">点我停止变换</button></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',data:{opacity:1},methods: {stop(){this.$destroy()}},//Vue完成模板的解析并把初始的真实DOM元素放入页面后(挂载完毕)调用mountedmounted(){console.log('mounted',this)this.timer = setInterval(() => {console.log('setInterval')this.opacity -= 0.01if(this.opacity <= 0) this.opacity = 1},16)},beforeDestroy() {clearInterval(this.timer)console.log('vm即将驾鹤西游了')},})</script>
</html>
3.路由
- 理解: 一个路由(route)就是一组映射关系(key - value),多个路由需要路由器(router)进行管理。
- 前端路由:key是路径,value是组件。
1.基本使用
-
安装vue-router,命令:
npm i vue-router
-
应用插件:
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>
2.几个注意点
- 路由组件通常存放在
pages
文件夹,一般组件通常存放在components
文件夹。 - 通过切换,“隐藏”了的路由组件,默认是被销毁掉的,需要的时候再去挂载。
- 每个组件都有自己的
$route
属性,里面存储着自己的路由信息。 - 整个应用只有一个router,可以通过组件的
$router
属性获取到。
3.多级路由(多级路由)
-
配置路由规则,使用children配置项:
routes:[{path:'/about',component:About,},{path:'/home',component:Home,children:[ //通过children配置子级路由{path:'news', //此处一定不要写:/newscomponent:News},{path:'message',//此处一定不要写:/messagecomponent:Message}]} ]
-
跳转(要写完整路径):
<router-link to="/home/news">News</router-link>
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
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>
-
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
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}}
}
8.<router-link>
的replace属性
- 作用:控制路由跳转时操作浏览器历史记录的模式
- 浏览器的历史记录有两种写入方式:分别为
push
和replace
,push
是追加历史记录,replace
是替换当前记录。路由跳转时候默认为push
- 如何开启
replace
模式:<router-link replace .......>News</router-link>
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() //可前进也可后退
10.缓存路由组件
-
作用:让不展示的路由组件保持挂载,不被销毁。
-
具体编码:
<keep-alive include="News"> <router-view></router-view> </keep-alive>
11.两个新的生命周期钩子
- 作用:路由组件所独有的两个钩子,用于捕获路由组件的激活状态。
- 具体名字:
activated
路由组件被激活时触发。deactivated
路由组件失活时触发。
8.<router-link>
的replace属性
- 作用:控制路由跳转时操作浏览器历史记录的模式
- 浏览器的历史记录有两种写入方式:分别为
push
和replace
,push
是追加历史记录,replace
是替换当前记录。路由跳转时候默认为push
- 如何开启
replace
模式:<router-link replace .......>News</router-link>
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() //可前进也可后退
10.缓存路由组件
-
作用:让不展示的路由组件保持挂载,不被销毁。
-
具体编码:
<keep-alive include="News"> <router-view></router-view> </keep-alive>
11.两个新的生命周期钩子
- 作用:路由组件所独有的两个钩子,用于捕获路由组件的激活状态。
- 具体名字:
activated
路由组件被激活时触发。deactivated
路由组件失活时触发。
更多推荐
Vue学习入门(三)
发布评论