Vue 0基础学习路线(22)—— 图解深度详述vue的路由组件传参和传参默认处理模式、对象模式、回调函数模式三种方式及详细案例(附详细案例代码解析过程及版本迭代过程)

1. 重点提炼

  • 路由组件传参
    • 默认处理模式
    • 对象模式
    • 回调函数模式

2. 路由组件传参

我们通常把路由直接映射(绑定)的组件称为 路由组件,也只有路由组件才能直接调用路由有关对象:$router$route

当我们一个组件即希望作为路由组件使用,又可能作为功能组件(某个页面中的一部分)去使用,这个时候路由组件传参的方式来做到这点

2.1 example01

假如数据很多,必然需要分页,做一个分页组件,即功能型组件,不可能单独是一个页面。 =>

实现分页

2.1.1 example01-1

我们可以组件内守卫的beforeRouteEnter 发生请求 => 替换created生命周期

\app\src\components\Page.vue

<template>
 
    <div class="pages">
        <span>1</span>
        <span>2</span>
        <span>3</span>
        <span>4</span>
        <span>5</span>
    </div>
 
</template>
 
<script>
    export default {
        name: "Page"
    }
</script>
 
<style scoped>
    .pages {
        margin: 20px 0;
    }
</style>

导入分页组件,并挂载进去

\app\src\views\Home.vue

<template>
    <div>
        <h2>商品列表</h2>
        <select @change="changeSort" :value="sort">
            <option value="desc">从高到低</option>
            <option value="asc">从低到高</option>
        </select>

        <Page></Page>

        <ul class="item-list">
            <li class="head">
                <span>名称</span>
                <span>价格</span>
                <span>操作</span>
            </li>
            <li v-for="item of items" :key="item.id">
                <span>
                    <router-link :to="{name: 'view', params: {id: item.id}}">{{item.name}}</router-link>
                </span>
                <span>{{item.price|RMB}}</span>
                <span>
                    <button>添加到购物车</button>
                </span>
            </li>
        </ul>
    </div>
</template>

<script>
    import * as apis from '@/apis'
    import {RMB} from "@/filters/RMB";
    import Page from "@/components/Page"

    export default {
        name: "Home",

        data() {
            return {
                sort: 'desc',
                items: []
            }
        },

        // 局部过滤器引入,挂载到filters
        filters: {
            RMB
        },

        components:{
            Page
        },

        beforeRouteEnter(to, from, next) {
            next(function(vm) {
                console.log(vm);
                vm.getItems();
            });
        },

        beforeRouteUpdate(to, from, next) {
            console.log('...', this.$route.query.sort)
            next();
            this.getItems();
        },

        methods: {
            changeSort({target: {value}}) {
                this.$router.push({
                    name: 'home',
                    query: {
                        sort: value
                    }
                });
            },

            async getItems() {
                console.log("...methods-getItems");
                this.sort = this.$route.query.sort || 'desc';
                let rs = await apis.getItems(this.sort);

                this.items = rs.data;
            }
        }
    }
</script>

<style>
    ul {
        margin: 0;
        padding: 0;
    }

    li {
        list-style: none;
    }

    .item-list li {
        padding: 10px;
        display: flex;
        justify-content: space-between;
        height: 30px;
        line-height: 30px;
        border-bottom: 1px dotted #333;
    }
    .item-list li.head {
        font-weight: bold;
    }
    .item-list li span {
        min-width: 200px;
    }
</style>

在这里插入图片描述

参考:https://https://github.com/6xiaoDi/blog-vue-Novice/tree/a2.08
Branch: branch06

commit description:a2.08(example01-1——分页组件框子)

tag:a2.08

2.1.2 example01-2

太丑:大致改改样式

\app\src\components\Page.vue

<template>

    <div class="pages">
        <span class="current">1</span>
        <span>2</span>
        <span>3</span>
        <span>4</span>
        <span>5</span>
    </div>

</template>

<script>
    export default {
        name: "Page"
    }
</script>

<style scoped>
    .pages {
        margin: 20px 0;
    }

    span {
        text-align: center;
        cursor: pointer;
        padding: 10px 20px;
        margin: 10px;
        border: 1px solid #000000;
    }
    /*高亮当前页*/
    span.current {
        cursor: default;
        background: rgba(0,255,255, .5);
    }
</style>

在这里插入图片描述

参考:https://https://github.com/6xiaoDi/blog-vue-Novice/tree/a2.09
Branch: branch06

commit description:a2.09(example01-2——分页组件框子-优化样式)

tag:a2.09

2.1.3 example01-3

分页必然需要点击,我们得准备当前页这个数据 => page : 1

分页里的总页数 => pages:10 => required: true // 必须传参

分页里的数据是不定死的,由外界传进来,并且Props验证为Number

v-for动态生成需要的分页树

class="{current: i === page} => current到底添不添加需要判断当前页 循环过程中的页码数与传进来的当前页是否相当,如果等就加current => 高亮

\app\src\views\Home.vue

<template>
    <div>
        <h2>商品列表</h2>
        <select @change="changeSort" :value="sort">
            <option value="desc">从高到低</option>
            <option value="asc">从低到高</option>
        </select>

        <Page :page="page" :pages="pages"></Page>

        <ul class="item-list">
            <li class="head">
                <span>名称</span>
                <span>价格</span>
                <span>操作</span>
            </li>
            <li v-for="item of items" :key="item.id">
                <span>
                    <router-link :to="{name: 'view', params: {id: item.id}}">{{item.name}}</router-link>
                </span>
                <span>{{item.price|RMB}}</span>
                <span>
                    <button>添加到购物车</button>
                </span>
            </li>
        </ul>
    </div>
</template>

<script>
    import * as apis from '@/apis'
    import {RMB} from "@/filters/RMB";
    import Page from "@/components/Page"

    export default {
        name: "Home",

        data() {
            return {
                sort: 'desc',
                items: [],
                page:1,
                pages:10
            }
        },

        // 局部过滤器引入,挂载到filters
        filters: {
            RMB
        },

        components:{
            Page
        },

        beforeRouteEnter(to, from, next) {
            next(function(vm) {
                console.log(vm);
                vm.getItems();
            });
        },

        beforeRouteUpdate(to, from, next) {
            console.log('...', this.$route.query.sort)
            next();
            this.getItems();
        },

        methods: {
            changeSort({target: {value}}) {
                this.$router.push({
                    name: 'home',
                    query: {
                        sort: value
                    }
                });
            },

            async getItems() {
                console.log("...methods-getItems");
                this.sort = this.$route.query.sort || 'desc';
                let rs = await apis.getItems(this.sort);

                this.items = rs.data;
            }
        }
    }
</script>

<style>
    ul {
        margin: 0;
        padding: 0;
    }

    li {
        list-style: none;
    }

    .item-list li {
        padding: 10px;
        display: flex;
        justify-content: space-between;
        height: 30px;
        line-height: 30px;
        border-bottom: 1px dotted #333;
    }
    .item-list li.head {
        font-weight: bold;
    }
    .item-list li span {
        min-width: 200px;
    }
</style>

\app\src\components\Page.vue

<template>

    <div class="pages">
        <span v-for="i of pages" :class="{current: i === page}">
            {{i}}
        </span>
    </div>

</template>

<script>
    export default {
        name: "Page",

        props: {
            page: {
                type: Number,
                default: 1
            },
            pages: {
                type: Number,
                required: true // 必须传参
            }
        },

        data() {
            return {};
        }
    }
</script>

<style scoped>
    .pages {
        margin: 20px 0;
    }

    span {
        text-align: center;
        cursor: pointer;
        padding: 10px 20px;
        margin: 10px;
        border: 1px solid #000000;
    }
    /*高亮当前页*/
    span.current {
        cursor: default;
        background: rgba(0,255,255, .5);
    }
</style>

在这里插入图片描述

参考:https://https://github.com/6xiaoDi/blog-vue-Novice/tree/a2.10
Branch: branch06

commit description:a2.10(example01-3——分页组件框子-优化样式)

tag:a2.10

2.1.4 example01-4

分页需要实现点击效果,点击之后跳转分页看对应的内容。那这个分页点击之后,该如何处理呢?

可以加一个点击事件 => changePage(i)

怎么跳转页码 =>

1、queryString => ?page=1

2、params=> 1

这里使用queryString => 在父级不要把page定死,而是queryString更改的时候更新page,当路由更改的时候,首次进入的时候需要获取queryString并在设置page,当页面刷新即发生beforeRouteUpdate的时候,也需要获取并更新page

可在getItems添加 => this.page = Number(this.$route.query.page) || 1;

同时后端也需要配上此效果,否则分页的数据也必然有问题,这里后端此功能没做,我们只需要看效果即可。

根据urlqueryString确定page的值,然后确定当前是第几页,紧接着向后端发送数据请求,接过来数据后重新渲染页面即可完成整个过程了。

\app\src\views\Home.vue

        methods: {
            changeSort({target: {value}}) {
                this.$router.push({
                    name: 'home',
                    query: {
                        sort: value
                    }
                });
            },

            async getItems() {
                this.page = Number(this.$route.query.page) || 1;
                this.sort = this.$route.query.sort || 'desc';
                let rs = await apis.getItems(this.sort);

                this.items = rs.data;
            }
        }

参考:https://https://github.com/6xiaoDi/blog-vue-Novice/tree/a2.11
Branch: branch06

commit description:a2.11(example01-4——根据queryString动态切换当前页码)

tag:a2.11

2.1.5 example01-5

已经实现直接根据url跳转页面了,现在继续往下实现点击事件。一点击就改变QueryStringpage值,那如何修改呢?

changePage()可以接收一个值(该span的页码),我们点击打印看看,刚好一一对应。

\app\src\components\Page.vue

<template>

    <div class="pages">
        <span v-for="i of pages" :class="{current: i === page}" @click="changePage(i)">
            {{i}}
        </span>
    </div>

</template>

<script>
    export default {
        name: "Page",

        props: {
            page: {
                type: Number,
                default: 1
            },
            pages: {
                type: Number,
                required: true // 必须传参
            }
        },

        data() {
            return {};
        },

        methods: {
            changePage(v) {
                console.log(v);
            }
        }
    }
</script>

<style scoped>
    .pages {
        margin: 20px 0;
    }

    span {
        text-align: center;
        cursor: pointer;
        padding: 10px 20px;
        margin: 10px;
        border: 1px solid #000000;
    }
    /*高亮当前页*/
    span.current {
        cursor: default;
        background: rgba(0,255,255, .5);
    }
</style>

在这里插入图片描述

参考:https://https://github.com/6xiaoDi/blog-vue-Novice/tree/a2.12
Branch: branch06

commit description:a2.12(example01-5——获取点击的页码值)

tag:a2.12

2.1.6 example01-6

我们点击以后,这些数字需要跑到queryString上,即重新改变请求的url

\app\src\components\Page.vue

            changePage(v) {
                console.log(this.$router);
                this.$router.push({
                    name: 'home',
                    query: {
                        page: v
                    }
                });
            }

在这里插入图片描述

按照以上设计,分页组件并没有达到最完美的效果。

我们跳转的目标地址是写死的(可能在其他页面分页后url就不是当前的页面url了),最好的方式其实是作为参数传进page组件标签上。

参考:https://https://github.com/6xiaoDi/blog-vue-Novice/tree/a2.13
Branch: branch06

commit description:a2.13(example01-6——点击页码后推送至url)

tag:a2.13

3. 案例

我们对 item.vue 组件进行改造,当我们在 home.vue 的商品列表上移入移出,出现商品信息提示层

在这里插入图片描述

// Home.vue
<template>
	...
  <li v-for="item of items" :key="item.id">
    <span>
      <router-link @mouseover.native="mouseover(item.id, $event)" @mouseout.native="mouseout(item.id, $event)" :to='{name: "item", params:{itemId: item.id}}'>{{item.name}}</router-link>
    </span>
    <span>{{item.price|RMB}}</span>
    <span>
      <button>添加到购物车</button>
    </span>
  </li>
	...
	<div class="tip" :style="{left: tip.left, top: tip.top}" v-show="tip.isShow">
    <Item :itemId="tip.itemId"></Item>
  </div>
	...
</template>
<script>
...
export default {
  ...,
  data() {
    return {
      items: [],
      tip: {
        itemId: 0,
        isShow: false,
        left: 0,
        top: 0
      }
    }
  },
  ...
  methods: {
    ...,
    mouseover(itemId, e) {
      let pos = e.target.getBoundingClientRect();
      this.tip.itemId = itemId;
      this.tip.left = pos.left + pos.width + 10 + 'px';
      this.tip.top = pos.top + 'px';
      this.tip.isShow = true;
    },
    mouseout(itemId, e) {
      this.tip.isShow = false;
    }
  }
}
</script>
<style>
...
.tip {
  position: fixed;
  left: 0;
  top: 0;
  border: 1px solid #000;
  background: #fff;
  padding: 10px;
}
</style>

因为原来的 Item.vue 组件时通过 this.$route.params.itemId 来接收 itemId 的,但是作为功能组件 itemId 需要通过 prop 来传入了,这个时候,我们需要对 Item.vue 组件进行改造

<template>
    <div>
        <template v-if="item">
            <h2>商品详情 - {{item.name}}</h2>
            <dt>ID</dt>
            <dd>{{item.id}}</dd>
            <dt>名称</dt>
            <dd>{{item.name}}</dd>
            <dt>价格</dt>
            <dd>{{item.price|RMB}}</dd>
        </template>
        <template v-else>
            <h2>没有该商品信息</h2>
        </template>
    </div>
</template>
<script>
import axios from 'axios';
import {RMB} from '@/filters/RMB';
export default {
    name: 'item',
    props: ['itemId'],
    data() {
        return {
            item: null
        }
    },
    filters: {
        RMB
    },
    watch: {
        itemId() {
            this.getItem();
        }
    },
    created() {
        // let itemId = Number(this.$route.params.itemId);
        this.getItem();
    },
    methods: {
        getItem() {
            if (this.itemId) {
                axios({
                    url: `/api/item/${this.itemId}`
                }).then(res => {
                    this.item = res.data;
                }).catch(err=>{});
            }
        }
    }
}
</script>

但是这个时候,我们的 Item.vue 可以接收来自 props 的参数,却不可以处理来自路由的 params 参数了。为了能给让 Item.vue 组件既能接收 props 传递的参数,也能接收 route.params 传递的参数,需要对 路由 也进行一些改造

{
  path: '/item/:itemId',
  name: 'item',
  component: Item,
  props: true
}

4. 默认处理

props 设置 为 true,那么 route.params 中的数据自动就会被设置为组件属性与组件原有 props 进行合并

5. 对象模式的

我们也可以有选择的返回 props

{
  path: '/item/:itemId',
  name: 'item',
  component: Item,
  props: {a: 1, b: 2}
}

6. 回调函数模式

也可以使用回调函数模式

{
  path: '/item/:itemId',
  name: 'item',
  component: Item,
  props: r => ({ itemId: Number(r.params.itemId) })
}

7. example02

我们在开发页面的时候,经常要做views视图组件,同时还需要些复用性组件,当然在上面的例子当中,可以看出来,视图组件和复用性组件功能分得还是很开的,互不干扰。但是有的时候会有一些问题,有些组件既可以当做视图组件来用,比如通过url直接访问它,同时它也还是可复用性的组件,这种情形下如何设计呢?是不是在components中写一个,又在views中又写一个呢? => 写两个,这样显然太弱智了。

当我们点击商品的时候,能在当前页面弹出一个对话框,我们先在名称后面加一个按钮,点击弹出详情信息对话框,我们先把它的结构进行封装。

7.1 example02-1

定义一个tip对象,在其中定义lefttop属性,再定一个属性,是否显示对话框,默认为false

样式直接拷贝我们上方的参考案例即可

\app\src\views\Home.vue

<template>
    <div>
        <h2>商品列表</h2>
        <select @change="changeSort" :value="sort">
            <option value="desc">从高到低</option>
            <option value="asc">从低到高</option>
        </select>

        <Page :page="page" :pages="pages"></Page>

        <ul class="item-list">
            <li class="head">
                <span>名称</span>
                <span>价格</span>
                <span>操作</span>
            </li>
            <li v-for="item of items" :key="item.id">
                <span>
                    <router-link :to="{name: 'view', params: {id: item.id}}">{{item.name}}</router-link>
                </span>
                <span>{{item.price|RMB}}</span>
                <span>
                    <button>添加到购物车</button>
                </span>
            </li>
        </ul>
        <div class="tip" :style="{left: tip.left, top: tip.top}" v-show="tip.isShow">
            ddddddddddddddddddddddddddddddd
        </div>
    </div>
</template>

<script>
    import * as apis from '@/apis'
    import {RMB} from "@/filters/RMB";
    import Page from "@/components/Page"

    export default {
        name: "Home",

        data() {
            return {
                sort: 'desc',
                items: [],
                page:1,
                pages:10,
                tip: {
                    left: 0,
                    top: 0,
                    isShow: true
                }
            }
        },

        // 局部过滤器引入,挂载到filters
        filters: {
            RMB
        },

        components:{
            Page
        },

        beforeRouteEnter(to, from, next) {
            next(function(vm) {
                console.log(vm);
                vm.getItems();
            });
        },

        beforeRouteUpdate(to, from, next) {
            console.log('...', this.$route.query.sort)
            next();
            this.getItems();
        },

        methods: {
            changeSort({target: {value}}) {
                this.$router.push({
                    name: 'home',
                    query: {
                        sort: value
                    }
                });
            },

            async getItems() {
                this.page = Number(this.$route.query.page) || 1;
                this.sort = this.$route.query.sort || 'desc';
                let rs = await apis.getItems(this.sort);

                this.items = rs.data;
            }
        }
    }
</script>

<style>
    ul {
        margin: 0;
        padding: 0;
    }

    li {
        list-style: none;
    }

    .item-list li {
        padding: 10px;
        display: flex;
        justify-content: space-between;
        height: 30px;
        line-height: 30px;
        border-bottom: 1px dotted #333;
    }
    .item-list li.head {
        font-weight: bold;
    }
    .item-list li span {
        min-width: 200px;
    }
    .tip {
        position: fixed;
        left: 0;
        top: 0;
        border: 1px solid #000;
        background: #fff;
        padding: 10px;
    }
</style>

在这里插入图片描述

参考:https://https://github.com/6xiaoDi/blog-vue-Novice/tree/a2.14
Branch: branch06

commit description:a2.14(example02-1——对话框框子)

tag:a2.14

7.2 example02-2

我们需要给每个按钮绑定点击事件 => isShowtrue即可

我们点击弹出弹框,希望根据当前的元素可以进行定位

获取按钮的位置,从当前点击的元素上获取即可,将对话框弹出位置,设置在按钮的后面

\app\src\views\Home.vue

<template>
    <div>
        <h2>商品列表</h2>
        <select @change="changeSort" :value="sort">
            <option value="desc">从高到低</option>
            <option value="asc">从低到高</option>
        </select>

        <Page :page="page" :pages="pages"></Page>

        <ul class="item-list">
            <li class="head">
                <span>名称</span>
                <span>价格</span>
                <span>操作</span>
            </li>
            <li v-for="item of items" :key="item.id">
                <span>
                    <router-link :to="{name: 'view', params: {id: item.id}}">{{item.name}}</router-link>
                    <button @click="showTip">点击查看详情</button>
                </span>
                <span>{{item.price|RMB}}</span>
                <span>
                    <button>添加到购物车</button>
                </span>
            </li>
        </ul>
        <div class="tip" :style="{left: tip.left, top: tip.top}" v-show="tip.isShow">
            ddddddddddddddddddddddddddddddd
        </div>
    </div>
</template>

<script>
    import * as apis from '@/apis'
    import {RMB} from "@/filters/RMB";
    import Page from "@/components/Page"

    export default {
        name: "Home",

        data() {
            return {
                sort: 'desc',
                items: [],
                page:1,
                pages:10,
                tip: {
                    left: 0,
                    top: 0,
                    isShow: false
                }
            }
        },

        // 局部过滤器引入,挂载到filters
        filters: {
            RMB
        },

        components:{
            Page
        },

        beforeRouteEnter(to, from, next) {
            next(function(vm) {
                console.log(vm);
                vm.getItems();
            });
        },

        beforeRouteUpdate(to, from, next) {
            console.log('...', this.$route.query.sort)
            next();
            this.getItems();
        },

        methods: {
            changeSort({target: {value}}) {
                this.$router.push({
                    name: 'home',
                    query: {
                        sort: value
                    }
                });
            },

            async getItems() {
                this.page = Number(this.$route.query.page) || 1;
                this.sort = this.$route.query.sort || 'desc';
                let rs = await apis.getItems(this.sort);

                this.items = rs.data;
            },

            showTip(e) {
                console.log(e.target);
                let {left: L, top: T} = e.target.getBoundingClientRect();

                this.tip = {
                    left: L +'px',
                    top: T + 'px',
                    isShow: true
                }
            }
        }
    }
</script>

<style>
    ul {
        margin: 0;
        padding: 0;
    }

    li {
        list-style: none;
    }

    .item-list li {
        padding: 10px;
        display: flex;
        justify-content: space-between;
        height: 30px;
        line-height: 30px;
        border-bottom: 1px dotted #333;
    }
    .item-list li.head {
        font-weight: bold;
    }
    .item-list li span {
        min-width: 200px;
    }
    .tip {
        position: fixed;
        left: 0;
        top: 0;
        border: 1px solid #000;
        background: #fff;
        padding: 10px;
    }
</style>

在这里插入图片描述

可弹出在按钮的下方

                this.tip = {
                    left: L +'px',
                    top: T + e.target.offsetHeight +  'px',
                    isShow: true
                }

在这里插入图片描述

参考:https://https://github.com/6xiaoDi/blog-vue-Novice/tree/a2.15
Branch: branch06

commit description:a2.15(example02-2——对话框框子设置位置)

tag:a2.15

7.3 example02-3

我们把后端的延时效果去掉

开始实现功能 => 点击按钮发请求

实际请求的数据也点击标签的数据一样,所以我们肯定希望views下的Detail组件是可以复用的。 => 它即可以作为视图组件,又可作可复用的功能组件去使用。

我们就不显示数据dddddddddddddddddddddd,而是将Detail组件复用过来。

<template>
    <div>
        <h2>商品列表</h2>
        <select @change="changeSort" :value="sort">
            <option value="desc">从高到低</option>
            <option value="asc">从低到高</option>
        </select>

        <Page :page="page" :pages="pages"></Page>

        <ul class="item-list">
            <li class="head">
                <span>名称</span>
                <span>价格</span>
                <span>操作</span>
            </li>
            <li v-for="item of items" :key="item.id">
                <span>
                    <router-link :to="{name: 'view', params: {id: item.id}}">{{item.name}}</router-link>
                    <button @click="showTip">点击查看详情</button>
                </span>
                <span>{{item.price|RMB}}</span>
                <span>
                    <button>添加到购物车</button>
                </span>
            </li>
        </ul>
        <div class="tip" :style="{left: tip.left, top: tip.top}" v-show="tip.isShow">
            <Detail/>
        </div>
    </div>
</template>

<script>
    import * as apis from '@/apis'
    import {RMB} from "@/filters/RMB";
    import Page from "@/components/Page"
    import Detail from '@/views/Detail';

    export default {
        name: "Home",

        data() {
            return {
                sort: 'desc',
                items: [],
                page:1,
                pages:10,
                tip: {
                    left: 0,
                    top: 0,
                    isShow: false
                }
            }
        },

        // 局部过滤器引入,挂载到filters
        filters: {
            RMB
        },

        components:{
            Page,
            Detail
        },

        beforeRouteEnter(to, from, next) {
            next(function(vm) {
                console.log(vm);
                vm.getItems();
            });
        },

        beforeRouteUpdate(to, from, next) {
            console.log('...', this.$route.query.sort)
            next();
            this.getItems();
        },

        methods: {
            changeSort({target: {value}}) {
                this.$router.push({
                    name: 'home',
                    query: {
                        sort: value
                    }
                });
            },

            async getItems() {
                this.page = Number(this.$route.query.page) || 1;
                this.sort = this.$route.query.sort || 'desc';
                let rs = await apis.getItems(this.sort);

                this.items = rs.data;
            },

            showTip(e) {
                console.log(e.target);
                let {left: L, top: T} = e.target.getBoundingClientRect();

                this.tip = {
                    left: L +'px',
                    top: T + e.target.offsetHeight +  'px',
                    isShow: true
                }
            }
        }
    }
</script>

<style>
    ul {
        margin: 0;
        padding: 0;
    }

    li {
        list-style: none;
    }

    .item-list li {
        padding: 10px;
        display: flex;
        justify-content: space-between;
        height: 30px;
        line-height: 30px;
        border-bottom: 1px dotted #333;
    }
    .item-list li.head {
        font-weight: bold;
    }
    .item-list li span {
        min-width: 200px;
    }
    .tip {
        position: fixed;
        left: 0;
        top: 0;
        border: 1px solid #000;
        background: #fff;
        padding: 10px;
    }
</style>

报错了,因为引入这个组件的时候,它发送请求了,但是它发送的请求是有问题的。

为啥一上来它就回去发请求呢?

因为tip显示,我们使用的是v-show。当我们使用v-show的时候,这个组件还是要渲染的,tip渲染的同时,也会把嵌套的Detail组件进行渲染。这个时候渲染就会发现一个问题,Detail组件一渲染,就立刻去发送请求,我们看Detail组件的代码。我们在其created生命周期,发送了请求。但是现在问题来了,我们当功能性组件的时候,并没有传参,没有传请求哪个id

实际现在就有两个问题需要解决了,第一个问题,我们别用v-show了,用v-if(频繁删除与销毁也不太好。

不过也可以在tip上用v-showDetail组件上用v-if,实际上对话框创建一次就好了,剩下显示与隐藏就够了。

在这里插入图片描述

 <div class="tip" :style="{left: tip.left, top: tip.top}" v-show="tip.isShow">
        <Detail v-if="tip.isShow"></Detail>
</div>

在这里插入图片描述

但是点击按钮还是会报错,因为没传递id。现在Detail组件不是作为页面组件,而是用作可复用功能组件。作为页面组件的话,Detail组件是在created生命周期通过urlparams获取id的。

在这里插入图片描述

参考:https://https://github.com/6xiaoDi/blog-vue-Novice/tree/a2.16
Branch: branch06

commit description:a2.16(example02-3——可复用组件没传id报错)

tag:a2.6

7.4 example02-4

可是现在的可复用组件,怎么传递id过去呢?

Home组件的data中的tip对象下增加id属性,初始化为0

点击按钮的时候,把id当参数,传给showTip事件处理函数,这个时候注意还需要手动添加$event事件对象。 => 更新data中的tip.id

<Detail v-if="tip.isShow" :id="tip.id"></Detail> => Detail组件上绑定data中的tip.id,传给Detail组件。

Home组件上都弄好了,现在在Detail组件中利用props接收id

\app\src\views\Home.vue

<template>
    <div>
        <h2>商品列表</h2>
        <select @change="changeSort" :value="sort">
            <option value="desc">从高到低</option>
            <option value="asc">从低到高</option>
        </select>

        <Page :page="page" :pages="pages"></Page>

        <ul class="item-list">
            <li class="head">
                <span>名称</span>
                <span>价格</span>
                <span>操作</span>
            </li>
            <li v-for="item of items" :key="item.id">
                <span>
                    <router-link :to="{name: 'view', params: {id: item.id}}">{{item.name}}</router-link>
                    <button @click="showTip(item.id, $event)">点击查看详情</button>
                </span>
                <span>{{item.price|RMB}}</span>
                <span>
                    <button>添加到购物车</button>
                </span>
            </li>
        </ul>
        <div class="tip" :style="{left: tip.left, top: tip.top}" v-show="tip.isShow">
            <Detail v-if="tip.isShow" :id="tip.id"></Detail>
        </div>
    </div>
</template>

<script>
    import * as apis from '@/apis'
    import {RMB} from "@/filters/RMB";
    import Page from "@/components/Page"
    import Detail from '@/views/Detail';

    export default {
        name: "Home",

        data() {
            return {
                sort: 'desc',
                items: [],
                page:1,
                pages:10,
                tip: {
                    id: 0,
                    left: 0,
                    top: 0,
                    isShow: false
                }
            }
        },

        // 局部过滤器引入,挂载到filters
        filters: {
            RMB
        },

        components:{
            Page,
            Detail
        },

        beforeRouteEnter(to, from, next) {
            next(function(vm) {
                console.log(vm);
                vm.getItems();
            });
        },

        beforeRouteUpdate(to, from, next) {
            console.log('...', this.$route.query.sort)
            next();
            this.getItems();
        },

        methods: {
            changeSort({target: {value}}) {
                this.$router.push({
                    name: 'home',
                    query: {
                        sort: value
                    }
                });
            },

            async getItems() {
                this.page = Number(this.$route.query.page) || 1;
                this.sort = this.$route.query.sort || 'desc';
                let rs = await apis.getItems(this.sort);

                this.items = rs.data;
            },

            showTip(id, e) {

                let {left: L, top: T} = e.target.getBoundingClientRect();

                this.tip = {
                    id,
                    left: L +'px',
                    top: T + e.target.offsetHeight +  'px',
                    isShow: true
                }
            }
        }
    }
</script>

<style>
    ul {
        margin: 0;
        padding: 0;
    }

    li {
        list-style: none;
    }

    .item-list li {
        padding: 10px;
        display: flex;
        justify-content: space-between;
        height: 30px;
        line-height: 30px;
        border-bottom: 1px dotted #333;
    }
    .item-list li.head {
        font-weight: bold;
    }
    .item-list li span {
        min-width: 200px;
    }
    .tip {
        position: fixed;
        left: 0;
        top: 0;
        border: 1px solid #000;
        background: #fff;
        padding: 10px;
    }
</style>

\app\src\views\Detail.vue

        async created() {
            // let id = this.$route.params.id;
            let id = this.id;
            let rs = await apis.getItem(id);

            this.item = rs.data;
        }

image-20200803212430358

现在对话框是没问题了,但是点击商品跳转详情页就出错了。

在这里插入图片描述

参考:https://https://github.com/6xiaoDi/blog-vue-Novice/tree/a2.17
Branch: branch06

commit description:a2.17(example02-4——未完全解决可复用组件没传id报错)

tag:a2.17

7.5 example02-5

这两者是矛盾的,那该怎么整?

\app\src\views\Detail.vue

      async created() {
            // let id = this.$route;
            let id = this.$route.params.id || this.id;
            // let id = this.$route.params.id;
 
            let rs = await apis.getItem(id);
 
            this.item = rs.data;
        }

现在就没问题了。

在这里插入图片描述

参考:https://https://github.com/6xiaoDi/blog-vue-Novice/tree/a2.18
Branch: branch06

commit description:a2.18(example02-5——解决可复用组件没传id报错)

tag:a2.18

7.6 example02-6

因为这种需求很多,vue提供了更好的方式。

这就是本节要学的东西,路由组件传参。它发现在组件当中有一个数据既可以通过路由url进行传递,又可以通过props进行传递,vue在这里帮助我们进行了合并。

props为主,它主要改的是路由上的东西 => 路由上的props属性设置为true => 它的意思就是自动把params中的数据合并到props中。

let id = this.$route.params.id || this.id; => let id = this.id;

\app\src\router\index.js

  {
            path: '/view/:id',
            name: 'view',
            component: Detail,
            props:true
        },

在这里插入图片描述

参考:https://https://github.com/6xiaoDi/blog-vue-Novice/tree/a2.19
Branch: branch06

commit description:a2.19(example02-6——用vue解决可复用组件没传id报错)

tag:a2.19

7.7 example02-7

还有一种方式可以选用对象的方式 => props直接设置为对象,这个对象里的值将会与props进行合并。

但是这里面可能有一个问题,我们再看一个例子。

\app\src\router\index.js

        {
            path: '/view/:id',
            name: 'view',
            component: Detail,
            // props:true
            props: {id:3, a:1}
        },

我们在Detail当中打印一下当前的数据看一下

        async created() {
            console.log(this);
            let id = this.id;
            let rs = await apis.getItem(id);
 
            this.item = rs.data;
        }

我们找vue组件对象下有id3的属性,但是没有找到a。

在这里插入图片描述

因为合并是以props为主的,我们得从props中取。

 export default {
        name: "Detail",

        props: ['id','a'],

        data() {
            return {
                item: null
            }
        },

        filters: {
            RMB
        },

        async created() {
            console.log(this);
            let id = this.id;
            let rs = await apis.getItem(id);

            this.item = rs.data;
        }
    }

在路由当中,props中设置的值 => Detail组件从路由中解析出来的值,对应的key值必须在props中,否则是不会合并进去的。

在这里插入图片描述

参考:https://https://github.com/6xiaoDi/blog-vue-Novice/tree/a2.20
Branch: branch06

commit description:a2.20(example02-7——用vue的对象的方式设置props)

tag:a2.20

7.8 example02-8

还有一种方式是通过回调函数的方式

props中的r对应就是$router对象 => 这样id就不用写死了。

        {
            path: '/view/:id',
            name: 'view',
            component: Detail,
            props(r) {
                // r $route
                return {
                    id: r.params.id,
                    a: 1
                }
            }
        },

在这里插入图片描述

参考:https://https://github.com/6xiaoDi/blog-vue-Novice/tree/a2.21
Branch: branch06

commit description:a2.21(example02-8——用vue的回调函数的方式设置props)

tag:a2.21

7.9 小结

props的三种方式,一种是设置为true,默认就从路由中解析

一种是写成返回固定的对象

还有一种是最为灵活的方式,可以进行很多逻辑处理,根据不同的逻辑返回不同的值。

考虑到在blog中不好体现代码更改的位置,小迪才用github托管代码,大家可以查看github,看到详细版本修改过程,搭配博客学习。



(后续待补充)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值