vue.js基础(5)

vue.js基础(5)

什么是路由

1.对于普通的网站,所有的超链接都是URL地址,所有的URL地址都对应服务器上对应的资源
2.对于单页面应用程序来说,主要通过URL中的hash(#号)来实现不同页面之间的切换,同时hash有一个特点:HTTP请求中不会包含hash相关 的内容,所以,单页面程序中页面跳转只要用hash实现
3.在单页面应用程序中,这种通过hash改变来切换页面的方式,称作前端路由(区别于后端路由)

在Vue中使用vue-router

1.导入vue-router组件类库
2.使用router-link组件来导航
3.使用router-view组件来显示匹配到的组件
4.创建使用vue.extend创建组件
5.创建一个卤藕router实例,通过routers属性来定义路由匹配规则
6.使用router属性来使用路由规则

<!DOCTYPE html>
<html lang="en">

	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title>路由的基本使用</title>
		<style type="text/css">
			.router-link-active,
			.myactive {
				color: red;
				background-color: #006400;
				font-style: italic;
				font-size: 80px;
				font-weight: 800;
				text-decoration: underline;
			}


			.v-enter,
			.v-leave-to {
				opacity: 0;
				transform: translateX(140px);
			}

			.v-enter-active,
			.v-leave-active {
				transition: all 0.8s ease;
			}
		</style>
		<script src="vue-2.4.0.js"></script>
		<!-- 安装路由模块 -->
		<script type="text/javascript" src="vue-router-3.0.1.js">

		</script>
	</head>

	<body>
		<div id="app">
<!-- router-link 默认渲染为一个a标签 tag属性可以改标签 -->
			<router-link to="/login" tag="span">登录组件</router-link>
			<router-link to="/register">注册组件</router-link>
			
			<!-- 这是vue-router 提供的元素,专门用来当作占位符的,将来路由规则匹配到的组件,就会展示到这个router-view 中去 -->
			<!-- 所以:我们可以把router-view 认为是一个占位符 -->
			<transition mode="out-in">
				<router-view></router-view>
			</transition>
		</div>
		<script>
			// 组建的 模板对象
			var login = {
				template: '<h1>登录组件</h1>'
			}
			var register = {
				template: '<h1>注册组件</h1>'
			}

// 创建一个路由对象,当导入vue-router 包之后,在window全局对象中,就有一个路由的构造函数,叫做VueRouter
// 在new路由对象的时候,可以为构造函数,传递一个配置对象
			var router = new VueRouter({
				// route 这个配置对象的route表示【路由匹配规则】的意思
				routes: [
					// 这里的redirect和node中的redirect完全是两码事
					{path:'/',redirect:"/login"},
					 //路由匹配规则
					// 每一个路由规则都是一个对象,这个规则对象身上有两个必须的属性:
					// 属性1是path ,表示监听哪个路由链接地址
					// 属性2是component ,表示如果路由是前面匹配到的path,则展示component 属性对应的那个组件
					// 注意:component的属性值,必须是一个组件的模板对象,不能是组件的引用名称
						{ path: '/login',
						component: login
					},
					{
						path: '/register',
						component: register
					}
				],
				linkActiveClass: 'myactive'
			})

			var vm = new Vue({
				el: '#app',
				data: {},
				methods: {},
				// router:router
				router  //将路由规则对象,注册到vm实例上,用来监听URL地址的变化,然后展示对应的组件
			});
		</script>
	</body>

</html>

在路由规则中定义参数

<!DOCTYPE html>
<html lang="en">

	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title>路由规则中定义参数</title>
		<script src="vue-2.4.0.js"></script>
		<script src="vue-router-3.0.1.js" type="text/javascript" charset="utf-8"></script>
	</head>

	<body>
		<div id="app">
			<!-- 如果在路由中,使用查询字符串,给路由传递参数,则不需要修改路由规则的path属性 -->
			<router-link to="/login?id=10&name=zs">登录</router-link>
			<router-link to="/register">注册</router-link>
			<router-view></router-view>
		</div>
		<script>
			// 组件的模板对象
			var login = {
				template: '<h1>登录组件----{{$route.query.id}}------{{$route.query.name}}</h1>'
			}
			var register = {
				template: '<h1>注册组件</h1>'
			}
			var router = new VueRouter({
				routes: [{
						path: '/login',
						component: login
					},
					{
						path: '/register',
						component: register
					}
				]
			})

			var vm = new Vue({
				el: '#app',
				data: {},
				methods: {},
				router
			});
		</script>
	</body>

</html>

<!DOCTYPE html>
<html lang="en">

	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title>路由的基本使用</title>
		<script src="vue-2.4.0.js"></script>
		<!-- 导入router包 -->
		<script type="text/javascript" src="vue-router-3.0.1.js">

		</script>
	</head>

	<body>
		<div id="app">
			<!-- 如果在路由中,使用查询字符串给路由传递参数,则不需要修改路由规则的path属性 -->
			<router-link to="/login/12/ls">登录</router-link>
			<router-link to="/register">注册</router-link>
			<router-view></router-view>
		</div>
		<script>
			var login = {
				// $route   
				template: '<h1>登录组件----{{$route.params.id}}----{{$route.params.name}}</h1>',

				data() {
					return {
						msg: '123'
					}
				},
				created() { //组件的生命周期钩子函数
					console.log(this.$route.params.id)
				}
			}
			var register = {
				template: '<h1>注册组件</h1>'
			}

			var router = new VueRouter({
				routes: [{
						path: '/login/:id/:name',
						component: login
					},
					{
						path: '/register',
						component: register
					},
				]
			})

			var vm = new Vue({
				el: '#app',
				data: {},
				methods: {},
				// router:router
				router
			});
		</script>
	</body>

</html>

使用children属性实现路由嵌套

<!DOCTYPE html>
<html lang="en">

	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title>路由的嵌套</title>
		<script src="vue-2.4.0.js"></script>
		<script src="vue-router-3.0.1.js" type="text/javascript" charset="utf-8"></script>
	</head>

	<body>
		<div id="app">
			<router-link to="/account">account</router-link>
			<router-view></router-view>
		</div>
		<template id="tmp">
			<div>
				<h1>account组件</h1>
				<router-link to="/account/login">登录</router-link>
				<router-link to="/account/register">注册</router-link>
				<router-view></router-view>
			</div>
		</template>
		<script>
			var account = {
				template: '#tmp'
			}
			var login = {
				template: '<h1>登录组件</h1>'
			}
			var register = {
				template: '<h1>注册组件</h1>'
			}
			var router = new VueRouter({
				routes: [{
					path: '/account',
					component: account,
					// 使用children属性,实现子路由,同时,子路由的path前面不带/,否则永远以根路径开始请求,这样不方便我们用户去理解URL地址
					children: [{
							path: 'login',
							component: login
						},
						{
							path: 'register',
							component: register
						}
					]
				}]
			})

			var vm = new Vue({
				el: '#app',
				data: {},
				methods: {},
				router
			});
		</script>
	</body>

</html>

在这里插入图片描述

命名视图实现经典布局

<!DOCTYPE html>
<html lang="en">

	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title>命名视图经典布局</title>
		<style type="text/css">
				
			*{
				margin: 0;
				padding: 0;
			}
			
				
			.header{
				width: 100%;
				height: 80px;
				background-color: #006400;
			}
			.container{
				display: flex;
				height: 700px;
			}
			.main{
				flex: 8;
				background-color: darkred;
			}
			.left{
				flex: 2;
				background-color: pink;
			}
			
		</style>
		<script src="vue-2.4.0.js"></script>
		<script src="vue-router-3.0.1.js" type="text/javascript" charset="utf-8"></script>
	</head>

	<body>
		<div id="app">
			<router-view class="header"></router-view>
			<div class="container">
			<router-view name="left" class="left"></router-view>
			<router-view name="main" class="main"></router-view>
		</div>
		</div>
		<script>
			var header = {
				template: '<h1>header头部区域</h1>'
			}
			var left = {
				template: '<h1>left侧边栏区域</h1>'
			}
			var main = {
				template: '<h1>main主体区域</h1>'
			}
// 创建路由对象
			var router = new VueRouter({
				routes: [{
					path: '/',
					components: {
						'default': header,
						'left': left,
						'main': main
					}
				}]
			})
			var vm = new Vue({
				el: '#app',
				data: {},
				methods: {},
				router
			});
		</script>
	</body>

</html>

在这里插入图片描述

watch 的使用

姓-名之间的监听

<!DOCTYPE html>
<html lang="en">

	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title>名称案例</title>
		<script src="vue-2.4.0.js"></script>
	</head>

	<body>
		<div id="app">
			<!--  分析: -->
			<!-- 1.我们要监听听到文本框数据的改变,这样才能知道什么时候去拼接出一个fullname -->
			<!-- 2.如何监听到文本框的数据改变 -->
			<!-- 第一种方式:keyup -->
			<!-- <input type="text" name="" id="" value="" v-model="firstname" @keyup="getfullname" />+
			<input type="text" name="" id="" value="" v-model="lastname" @keyup="getfullname" />=
			<input type="text" name="" id="" value="" v-model="fullname"  /> -->

			<!-- 第二种方式:watch -->
			<!-- 
			<input type="text" name="" id="" value="" v-model="firstname" />+
			<input type="text" name="" id="" value="" v-model="lastname" />=
			<input type="text" name="" id="" value="" v-model="fullname" /> -->

			<!-- 第三种方式:computed -->
			<input type="text" name="" id="" value="" v-model="firstname" />+
			<input type="text" name="" id="" value="" v-model="middlename" />+
			<input type="text" name="" id="" value="" v-model="lastname" />=
			<input type="text" name="" id="" value="" v-model="fullname" />


		</div>
		<script>
			var vm = new Vue({
				el: '#app',
				data: {
					firstname: '',
					lastname: '',
					middlename: ''
				},
				methods: {
					getfullname() {
						this.fullname = this.firstname + '-' + this.lastname
					}
				},
				// watch: { //使用这个属性,可以监视data中指定数据的变化,如何触发这个watch中对应的function处理函数
				// 	'firstname': function(newVal, oldVal) {
				// 		// console.log('监视到了firstname 的变化')
				// 		//  console.log(newVal+'----'oldVal)
				// 		this.fullname = newVal + '-' + this.lastname
				// 	},
				// 	'lastname': function(newVal, oldVal) {
				// 		this.fullname = this.firstname + '-' + this.lastname
				// 	}
				// }
				computed: { //在computed中,可以定义一些属性,这些属性叫做【计算属性】,计算属性的本质,就是一个方法,只不过,我们在使用这些计算属性的时候,是把他们的名称,直接当作普通属性去使用就好了
					// 注意1:计算属性,在引用的时候,一定不要加()去调用,直接把它当作普通属性去使用就好了
					// 注意2:只要计算属性,这个function内部,所用到的任何data中的数据发生了变化,就会立即重新计算这个计算属性的值
					// 注意3:计算属性的求值结果,会被缓存起来,方便下次直接使用,如果计算属性方法中,所有来的任何数据,都没有发生或变化,则不会重新对计算属性求值:
					'fullname': function() {
						console.log('ok')
						return this.firstname + '-' + this.middlename + '-' + this.lastname
					}
				}
			});
		</script>
	</body>

</html>

watch、computed和methods之间的对比

1.computed属性的结果会被缓存,除非依赖的响应式属性变化才会重新计算。主要当作属性来使用
2.methods方法表示一个具体的操作,主要书写业务逻辑
3.watch有一个对象,键是需要观察的表达式,值是对应回调函数。主要用来监听某些特定数据的变化,从而进行某些具体的业务逻辑操作,可以看作是computed和methods的结合体
在这里插入图片描述

这篇文章有 1,099 个评论

  1. roulette

    Hello There. I found your blog the use of msn. That
    is a very well written article. I will be
    sure to bookmark it and return to read extra of your helpful info.

    Thanks for the post. I will definitely return.

  2. Online Casino

    First off I would like to say superb blog! I had a quick question that I’d like
    to ask if you don’t mind. I was curious to find out how you center yourself and clear your
    mind prior to writing. I have had a hard time clearing my mind in getting my ideas out there.

    I truly do take pleasure in writing however it just seems like the first 10 to 15 minutes tend to
    be lost simply just trying to figure out how to begin. Any ideas or
    hints? Thank you!

  3. Trada Casino

    I am really inspired along with your writing talents as well as
    with the format on your weblog. Is this a paid theme or did you
    customize it your self? Either way keep up the excellent quality writing,
    it is rare to see a nice blog like this one these days..

  4. roulette

    Hello, after reading this remarkable piece of writing i am also happy to share my know-how here with colleagues.

  5. 코인 카지노

    This website certainly has all the information I wanted about
    this subject and didn’t know who to ask.

  6. Beatrice Reedy

    Aw, this was a very nice post. Taking a few
    minutes and actual effort to generate a top notch article… but
    what can I say… I hesitate a whole lot and don’t manage to get nearly anything done.

  7. 7Bit Casino

    I visit everyday some blogs and sites to read content, except this weblog presents quality
    based articles.

  8. 더킹 카지노

    A person necessarily assist to make significantly
    posts I’d state. That is the very first time
    I frequented your web page and thus far? I surprised with the research you made to create this particular submit incredible.
    Wonderful activity!

  9. 우리카지노

    When I initially commented I clicked the “Notify me when new comments are added”
    checkbox and now each time a comment is added I get three e-mails with the
    same comment. Is there any way you can remove people from that
    service? Appreciate it!

  10. slots

    I’m curious to find out what blog platform you have been utilizing?

    I’m experiencing some minor security issues with my latest website and I would like
    to find something more secure. Do you have any suggestions?

  11. 더킹 카지노

    I’m curious to find out what blog platform you are working with?
    I’m experiencing some small security issues with my latest website and I’d like
    to find something more risk-free. Do you have any recommendations?

  12. 1xbet

    I was suggested this website by my cousin. I am not sure whether this
    post is written by him as nobody else know such detailed about my
    problem. You’re wonderful! Thanks!

  13. 1xbet

    Hi there everyone, it’s my first pay a quick visit
    at this site, and post is actually fruitful designed for me, keep up posting these types of articles or
    reviews.

  14. 21 Casino

    Have you ever considered about including a little bit more than just your articles?
    I mean, what you say is valuable and all. However just imagine if you added some great pictures or videos to give your posts more, “pop”!
    Your content is excellent but with images and clips, this website could certainly be one of the most beneficial in its
    field. Terrific blog!

  15. Online Casino

    This post provides clear idea designed for the new viewers of blogging, that actually how
    to do running a blog.

  16. 카지노

    I am extremely impressed with your writing skills and also with the layout on your weblog.

    Is this a paid theme or did you modify it yourself? Anyway keep up the
    nice quality writing, it is rare to see a great blog like this one nowadays.

  17. roulette

    I do accept as true with all the concepts you’ve offered to your post.

    They are really convincing and can certainly work. Still, the posts are very short for novices.
    May you please lengthen them a bit from next time? Thanks for the post.

  18. 7Bit Casino

    This article presents clear idea designed for the new visitors of blogging, that
    actually how to do blogging.

  19. 우리카지노

    This is a topic that is near to my heart… Many thanks!

    Exactly where are your contact details though?

  20. 우리카지노

    I’m curious to find out what blog system you are using?
    I’m having some small security problems with my
    latest website and I would like to find
    something more safeguarded. Do you have any recommendations?

  21. 7Bit Casino

    It’s awesome designed for me to have a site, which is valuable in support of my knowledge.

    thanks admin

  22. 우리카지노

    Thanks for any other magnificent post. The place else could anybody get that type of info in such an ideal manner
    of writing? I’ve a presentation subsequent week, and I’m on the look for such information.

  23. Payday loans

    I’m more than happy to find this website. I
    need to to thank you for your time just for this fantastic read!!

    I definitely loved every little bit of it and i also
    have you saved to fav to check out new information in your site.

  24. 우리카지노

    whoah this blog is wonderful i really like reading your articles.
    Keep up the good work! You already know, many individuals are searching around for this information, you can help
    them greatly.

  25. 우리카지노

    May I simply say what a relief to uncover somebody who
    genuinely understands what they are discussing on the internet.
    You definitely realize how to bring a problem to light and make it important.
    More people should look at this and understand this side
    of your story. It’s surprising you’re not more popular since you definitely have the gift.

  26. slots

    It is actually a great and helpful piece of information.
    I’m happy that you shared this useful information with us.
    Please keep us informed like this. Thanks for sharing.

  27. 1xbet

    Thank you for the good writeup. It if truth be told used to be a enjoyment account it.
    Look complex to far introduced agreeable from you! By the way,
    how can we keep in touch?

  28. 카지노사이트

    You really make it appear so easy together with your presentation but I in finding this
    topic to be really one thing which I think I would never understand.
    It kind of feels too complicated and extremely wide
    for me. I am having a look forward to your next post, I’ll try to get the hang of
    it!

  29. Trada Casino

    I have been exploring for a little for any high-quality articles or weblog posts in this sort of house .
    Exploring in Yahoo I at last stumbled upon this site. Reading this info So
    i am happy to express that I have an incredibly excellent uncanny feeling
    I found out just what I needed. I most definitely will make certain to do not
    forget this site and provides it a look regularly.

  30. slots

    I was suggested this blog through my cousin. I’m no longer certain whether or not this publish
    is written through him as nobody else realize such specified approximately my trouble.

    You are amazing! Thanks!

  31. 7Bit Casino

    I like it when individuals come together and share opinions.
    Great blog, continue the good work!

  32. 7Bit Casino

    magnificent points altogether, you just gained a new reader.
    What could you recommend about your publish that you made some days in the past?
    Any certain?

  33. 21 Casino

    I couldn’t resist commenting. Well written!

  34. 1xbet

    I do trust all of the ideas you’ve presented in your post.
    They are very convincing and can definitely work.

    Still, the posts are too quick for novices. Could you please
    prolong them a little from next time? Thank you for the post.

  35. 우리카지노

    Aw, this was an exceptionally good post.

    Taking the time and actual effort to make a good article… but what can I say… I put things off a
    lot and never manage to get nearly anything done.

  36. 더킹 카지노

    Woah! I’m really enjoying the template/theme of this website.

    It’s simple, yet effective. A lot of times it’s hard to get
    that “perfect balance” between user friendliness
    and appearance. I must say you have done a superb job with this.
    In addition, the blog loads extremely fast for me on Firefox.
    Superb Blog!

  37. roulette

    Hello there, I discovered your blog by the use of Google whilst
    looking for a comparable matter, your website came up, it
    seems to be good. I have bookmarked it in my google
    bookmarks.
    Hi there, simply became aware of your blog thru Google,
    and found that it is truly informative. I am going to watch out for brussels.

    I’ll be grateful in case you continue this in future. Lots of people can be benefited out of your writing.
    Cheers!

  38. roulette

    Oh my goodness! Awesome article dude! Thank you, However I am experiencing issues with your RSS.
    I don’t understand the reason why I cannot subscribe to it.
    Is there anybody else getting identical RSS issues?

    Anyone who knows the answer will you kindly respond?
    Thanks!!

  39. 우리카지노

    Hi there, after reading this awesome paragraph i am too happy to share my
    knowledge here with colleagues.

  40. 더킹 카지노

    I was suggested this web site via my cousin. I’m no longer positive whether or not this post is written by
    way of him as no one else realize such special approximately my trouble.
    You are wonderful! Thanks!

  41. roulette

    This is really interesting, You’re a very skilled blogger.
    I’ve joined your rss feed and look forward to seeking more of
    your magnificent post. Also, I’ve shared your site in my social networks!

  42. 더킹카지노

    Aw, this was an incredibly nice post. Spending some time and actual effort to produce a very good
    article… but what can I say… I put things off a lot and never seem to get anything done.

  43. 바카라 사이트

    I’m truly enjoying the design and layout of your site.
    It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit
    more often. Did you hire out a developer to create your theme?
    Fantastic work!

  44. 모나코 카지노

    I go to see every day a few blogs and information sites to read posts,
    but this webpage offers quality based articles.

  45. 우리카지노

    Thanks for sharing your thoughts. I really appreciate your efforts and I will be waiting for your next write ups thank you once again.

  46. 더킹카지노

    I was suggested this blog by my cousin. I’m not sure whether this post is written by him
    as nobody else know such detailed about my problem.
    You are wonderful! Thanks!

  47. no deposit bonus

    Write more, thats all I have to say. Literally, it
    seems as though you relied on the video to make your point.

    You clearly know what youre talking about, why waste
    your intelligence on just posting videos to your
    weblog when you could be giving us something informative to read?

  48. 더킹카지노

    These are actually impressive ideas in concerning blogging.
    You have touched some fastidious things here. Any way keep up wrinting.

  49. 더나인카지노

    Excellent blog you have got here.. It’s hard to find high-quality writing like yours nowadays.

    I really appreciate individuals like you! Take care!!

发表评论