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. 더킹카지노

    Aw, this was an exceptionally nice post. Finding the time and actual effort to create a superb article… but what can I say… I hesitate a whole lot and don’t seem to get
    anything done.

  2. Do you mind if I quote a few of your articles as long as I provide
    credit and sources back to your site? My website is in the exact
    same area of interest as yours and my users would really benefit from a
    lot of the information you provide here. Please let me know if this okay
    with you. Thanks!

  3. カジノX

    Hi there! I just want to give you a huge thumbs up for your excellent information you’ve got right here on this post.

    I’ll be returning to your blog for more soon.

  4. 한국 야동

    I think this is one of the such a lot important info for me.
    And i’m happy reading your article. However should remark on few
    general issues, The web site taste is great, the articles is really nice :
    D. Excellent activity, cheers

  5. 오리엔탈 카지노

    I’m curious to find out what blog platform you happen to be utilizing?
    I’m experiencing some small security problems with my latest site
    and I’d like to find something more safeguarded.
    Do you have any suggestions?

  6. 베스트카지노

    Wow, wonderful blog layout! How long have you been blogging for?
    you make blogging look easy. The overall look of your web site is great,
    let alone the content!

  7. titanium rings

    Outstanding post however I was wondering if you could write a
    litte more on this topic? I’d be very thankful if you could elaborate a little bit
    more. Many thanks!

  8. 에비앙카지노

    I visit everyday a few blogs and sites to read articles, however this website gives feature based content.

  9. bet365 ログイン

    Hi to all, the contents present at this web page are
    genuinely awesome for people knowledge, well, keep up the nice work fellows.

  10. 메리트카지노

    Its like you read my mind! You seem to know a lot about this, like you wrote the book in it or something.
    I think that you could do with some pics to drive the message home a bit, but instead
    of that, this is fantastic blog. An excellent read.
    I will certainly be back.

  11. カジノミー

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

  12. 더나인카지노

    Hi, I wish for to subscribe for this blog to obtain latest updates, so where can i do it please help out.

  13. 카지노사이트

    Thankfulness to my father who stated to me concerning this web
    site, this weblog is really awesome.

  14. 빅카지노

    Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point.
    You obviously know what youre talking about, why waste
    your intelligence on just posting videos to your weblog when you could be giving us something enlightening to read?

  15. 더나인카지노

    It’s appropriate time to make some plans for the
    future and it is time to be happy. I have read this post and if I could I want to suggest
    you few interesting things or advice. Maybe you can write next articles referring to this article.
    I wish to read more things about it!

  16. 코인카지노

    Pretty section of content. I just stumbled upon your web site and in accession capital to assert that
    I acquire actually enjoyed account your blog posts.

    Any way I’ll be subscribing to your feeds and even I achievement you access
    consistently fast.

  17. 빅카지노

    I just like the valuable info you supply to your articles.
    I will bookmark your blog and take a look at again right here regularly.
    I’m reasonably certain I’ll be told many new stuff right right here!

    Good luck for the next!

  18. Titanium Trim

    It’s really a nice and useful piece of information. I am satisfied that you simply shared this useful information with us.
    Please stay us informed like this. Thanks for sharing.

  19. 메이드 pissing close up

    If some one wants expert view on the topic of running a blog then i recommend him/her to visit this webpage, Keep up the fastidious job.

  20. advertisement music

    Your way of telling the whole thing in this article is actually pleasant, all can easily
    know it, Thanks a lot.

  21. 우리카지노

    I seriously love your blog.. Excellent colors & theme.
    Did you build this web site yourself? Please reply back as I’m hoping to
    create my own personal blog and would love to find out where you got this from or just what the theme is named.
    Thanks!

  22. 빅카지노

    Hello there! I could have sworn I’ve been to
    this website before but after going through a few of the
    articles I realized it’s new to me. Regardless, I’m definitely delighted I discovered it and I’ll be bookmarking it and checking back frequently!

  23. code 1xbet

    I’m not that much of a online reader to be honest but your sites
    really nice, keep it up! I’ll go ahead and bookmark your website to come back in the future.
    All the best

  24. 1xbet

    If you wish for to get a great deal from this article then you have to apply these techniques to your won website.

  25. 카지노 룰렛

    I visited various blogs but the audio feature for audio songs present at this website
    is really marvelous.

  26. インターカジノ

    I do accept as true with all of the concepts you’ve
    presented in your post. They are really convincing and can certainly work.
    Nonetheless, the posts are too quick for starters.
    May you please extend them a bit from next time?

    Thanks for the post.

  27. 야동

    Keep on writing, great job!

  28. 퍼스트카지노

    I’m not sure where you are getting your information, but good topic.
    I needs to spend some time learning more or understanding more.
    Thanks for fantastic information I was looking for this
    information for my mission.

  29. 더나인카지노

    I’ve been exploring for a little for any high quality articles or blog posts on this sort of space .

    Exploring in Yahoo I at last stumbled upon this website. Studying this information So
    i’m satisfied to express that I’ve a very good uncanny feeling I found out just what I needed.

    I most definitely will make certain to don?t omit this website
    and give it a glance regularly.

  30. Happy Luke Casino

    Good day! This is my first comment here so I just wanted to give a
    quick shout out and tell you I really enjoy reading through
    your posts. Can you recommend any other blogs/websites/forums that deal with the same topics?
    Appreciate it!

  31. คาสิโนสด

    Hello there, You have done an incredible job. I’ll definitely digg it and personally suggest to
    my friends. I’m confident they will be benefited from this site.

  32. 더킹카지노

    It’s a shame you don’t have a donate button! I’d most certainly donate to
    this outstanding blog! I guess for now i’ll settle for book-marking
    and adding your RSS feed to my Google account. I look forward to new updates and will
    share this blog with my Facebook group. Chat soon!

  33. kèo nhà cái bóng đá

    Can I just say what a comfort to uncover someone
    who actually understands what they are talking about on the web.

    You definitely know how to bring an issue to light and make it important.
    More people have to read this and understand this side of your story.
    I can’t believe you’re not more popular given that you definitely have the gift.

发表评论