0
点赞
收藏
分享

微信扫一扫

Vue —— 项目实战总结(一)

捌柒陆壹 2022-05-31 阅读 58

文章目录


1. 创建项目
2. 目录内容
3. 路由的配置
	import router from '@/router'
	
	new Vue({
	  render: (h) => h(App),
	  router,
	}).$mount("#app");
	// 配置路由的地方
	import Vue from "vue";
	import VueRouter from "vue-router";
	
	// 使用路由插件
	Vue.use(VueRouter);
	// 引入路由组件
	import Home from "@/pages/Home";
	
	// 配置路由
	export default new VueRouter({
	  // 配置路由
	  routes: [
	    {
	      path: "/home",
	      component: Home,
	      meta: { show: true },
	    }
	    // 重定向,在项目跑起来的时候,访问/,立马让它指向首页
	    {
	      path: "*",
	      redirect: "/home",
	    },
	  ],
	});
4. 路由的跳转
	<router-link to='/xxx'></router-link>
	<button @click="xxx"></button>
	
	methods:{
		xxx() {
			this.$router.push(......)
		}
	}
5. 路由的元信息
	path: "/home",
    component: Home,
	meta: {show: true}
	.......
	<Footer v-show="$route.meta.show"/>
6. 路由传参
	path: "/search/:keyword"
	path: "/search"
	this.$router.push('/search/' + this.keyword + '?k=' + this.keyword.toUpperCase())
	this.$router.push(`/search/${this.keyword}?k=${this.keyword.toUpperCase()}`)
	this.$router.push({name: 'search', params: {keyword: this.keyword}, query:{k: this.keyword.toUpperCase()}})
    <div>
      <h1>params参数————{{ $route.params.keyword }}</h1>
      <h1>query参数————{{ $route.query.k }}</h1>
    </div>
7. 路由传参的面试题

答:路由跳转传参的时候,对象的写法可以是 name、 path 形式,但是需要注意的是,path 这种写法不能与 params 参数一起使用。

答:如果要求传递 params 参数,但是并没有传递,则地址栏的 URL 会有问题。我们可以在配置路由的时候,在占位符的后面加上一个问号 (path: "/search/:keyword?")【params 可以传递或者不传递】,此时地址栏的 URL 不会发生错误。

答:使用 undefined 解决:params 参数可以传参、不传参(空字符串)

	this.$router({name: 'search', params: {keyword: ''||undefined}, query: {k: this.keyword.toUpperCase()}})

答案:可以。

  1. 布尔值写法:只能传递 params 参数:props:true
  2. 对象写法:额外的给路由传递一些参数:props: {a: 1, b: 2}
  3. 函数写法:可以传递 params 参数,也可以传递 query 参数,通过 props 传递给路由组件。
	props: ($route) => ({keyword: $route.params.keyword, k: $route.query.k})
举报

相关推荐

0 条评论