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,784 个评论

  1. Cam4

    Undeniably imagine that that you said. Your favorite justification appeared to be on the net the easiest thing to be aware of.
    I say to you, I certainly get annoyed even as folks think about issues that they just don’t recognise about.
    You controlled to hit the nail upon the highest and defined out the entire thing with no need
    side effect , people could take a signal. Will likely be back to get more.
    Thanks

  2. lottery powerball jackpot

    Hey there! Do you know if they make any plugins to assist with SEO?

    I’m trying to get my blog to rank for some targeted keywords but I’m
    not seeing very good success. If you know of any please share.

    Thanks!

  3. gaming

    Hello! Quick question that’s totally off topic.

    Do you know how to make your site mobile friendly? My weblog looks weird when browsing
    from my iphone4. I’m trying to find a template or plugin that might
    be able to resolve this problem. If you have any suggestions, please share.
    Thank you!

  4. 더나인카지노

    I am really delighted to read this weblog posts which contains
    lots of helpful facts, thanks for providing these
    statistics.

  5. 우리카지노

    Hello There. I found your weblog using msn. This is a
    really smartly written article. I’ll be sure to bookmark it and come back to learn extra of
    your helpful information. Thanks for the post. I will certainly
    return.

  6. porno

    After I initially commented I seem to have clicked the -Notify me when new comments are added- checkbox and from now
    on every time a comment is added I get 4 emails with the
    exact same comment. There has to be an easy method you are
    able to remove me from that service? Many thanks!

  7. m88 mobile

    Nice post. I was checking constantly this blog and
    I’m impressed! Extremely useful info particularly the
    remaining phase 🙂 I maintain such information much.
    I was seeking this particular info for a long time. Thanks and best of luck.

  8. hair care manufacturer

    If you are going for most excellent contents like me, simply pay a quick visit this web
    page everyday for the reason that it provides quality contents,
    thanks

  9. skidmore dining hall

    I was recommended this blog through my cousin. I am now not sure whether this submit is written through him as nobody else know such distinctive about my trouble.
    You are amazing! Thanks!

  10. slot games

    When someone writes an paragraph he/she
    retains the plan of a user in his/her mind that how a user can know it.

    Thus that’s why this paragraph is amazing. Thanks!

  11. 퍼스트카지노

    I’m now not positive where you’re getting your information, but great
    topic. I must spend a while learning more or figuring out more.
    Thanks for excellent information I was searching for this information for
    my mission.

  12. repair and maintenance

    Greetings! Very helpful advice in this particular article!
    It’s the little changes which will make the greatest changes.
    Many thanks for sharing!

  13. カジノ セット

    You’re so awesome! I don’t believe I’ve truly read a single thing
    like this before. So great to find someone with unique
    thoughts on this topic. Really.. thanks for starting this up.

    This site is one thing that is needed on the internet, someone with a
    bit of originality!

  14. Thanks for a marvelous posting! I seriously enjoyed reading
    it, you happen to be a great author. I will be sure to bookmark your blog
    and may come back sometime soon. I want to encourage yourself to continue your great
    work, have a nice holiday weekend!

  15. casino

    bookmarked!!, I really like your website!

  16. sisal casinò

    Hello! This is kind of off topic but I need some
    advice from an established blog. Is it very difficult to set
    up your own blog? I’m not very techincal but I can figure things out pretty
    quick. I’m thinking about setting up my own but I’m not
    sure where to start. Do you have any points or suggestions?
    With thanks

  17. 바카라 사이트

    An impressive share! I’ve just forwarded this onto a coworker
    who has been doing a little homework on this.

    And he in fact ordered me breakfast simply because
    I discovered it for him… lol. So let me reword this….
    Thank YOU for the meal!! But yeah, thanx for spending some time to discuss this matter
    here on your web page.

  18. is 10cric legal in india

    Thanks for any other informative site. The place else may I get that type of info written in such an ideal means?
    I have a challenge that I’m simply now running on, and I’ve been at the look out for
    such information.

  19. indian betting sites

    I don’t even know how I ended up here, but I thought this post was great.
    I do not know who you are but certainly you’re going to a famous blogger if you are not already
    😉 Cheers!

  20. 빅카지노

    Hello there, I found your blog by the use of Google whilst searching
    for a related topic, your website got here up, it
    seems to be great. I have bookmarked it in my google bookmarks.

    Hello there, simply was alert to your weblog thru Google, and found that it is truly informative.
    I’m gonna watch out for brussels. I’ll be grateful
    for those who continue this in future. Lots of folks might be benefited
    out of your writing. Cheers!

  21. 더나인카지노

    Hi there! This is kind of off topic but I need some advice from an established
    blog. Is it hard to set up your own blog? I’m not
    very techincal but I can figure things out pretty fast.
    I’m thinking about setting up my own but I’m not sure where to
    begin. Do you have any tips or suggestions?

    With thanks

  22. aH8W1dR1xL3

    I constantly emailed this weblog post page to all my associates, for the reason that if like to read it afterward
    my friends will too.

  23. w88 poker ios

    Fascinating blog! Is your theme custom made or did you download it
    from somewhere? A design like yours with a few simple tweeks would really make
    my blog shine. Please let me know where you got your theme.
    Appreciate it

  24. 메리트카지노

    Hi I am so glad I found your web site, I really found you by accident, while I was
    searching on Aol for something else, Anyhow I am here now and
    would just like to say kudos for a fantastic post and a all round
    thrilling blog (I also love the theme/design),
    I don’t have time to go through it all at the moment but I have
    bookmarked it and also added your RSS feeds, so when I
    have time I will be back to read a great deal more, Please do keep
    up the excellent work.

  25. nhà cái uy tín

    Hello! I know this is kinda off topic but I was wondering which blog platform are you using
    for this site? I’m getting tired of WordPress because I’ve had issues with hackers and I’m looking at alternatives for another platform.
    I would be great if you could point me in the direction of
    a good platform.

  26. bet india

    Hi there to all, it’s genuinely a good for me to visit
    this site, it includes priceless Information.

发表评论