vue传参

作者: 輪徊傷 | 来源:发表于2022-02-09 09:25 被阅读0次

    一、路由传参

    1.1、 明文传参 ( 特点:URL路径 \color{red}{会} 显示传递的参数 )

    \color{red}{优点:页面刷新参数不会丢失}
    \color{red}{劣势:参数公开}

    路由跳转: 传递参数

    html 页面跳转
    <router-link
          :to="{ path: '/goodsDetail', query: { name: 'LBipanda', age: 22 } }"
    >XXX详情页</router-link>
    
    js 跳转
    this.$router.push({
        name: "GoodsDetail",
        // path: "/goodsDetail",
        query: {
            name: "Baby",
            age: 20,
        },
    });
    

    接收参数

    this.$route.query.XXXX
    

    1.2、 密文传参 ( 特点:URL路径 \color{red}{不会} 显示传递的参数 )

    \color{red}{优点:参数不公开}
    \color{red}{劣势:页面刷新参数会丢失}

    路由跳转: 传递参数

    html 页面跳转
    <router-link
          :to="{ name: 'GoodsDetail', params: { name: 'CatGod', age: 20 } }"
    >XXX详情页</router-link>
    
    js 跳转
    this.$router.push({
     必须选择 name 来传参,不然获取不到数据。明文传参则没有这个限制(name、path都行)
        name: "GoodsDetail",
        params: {
            name: "Dog",
            age: 20,
        },
    });
    

    接收参数

    this.$route.params.XXXX
    

    1.3、 冒号的形式传递参数

    \color{red}{优点:页面刷新参数不会丢失}
    \color{red}{劣势:需要在路由 一一配置}

    路由跳转: 传递参数

    路由配置
    {
        path: '/goodsDetailTwo/:name/:age', 需要通过 /: 的形式配置
        component: () => import("@/views/home/goods-detailTwo")
    },
    
    html 页面跳转
    <router-link
          :to="{ path: `/goodsDetailTwo/${man.name}/${man.age}` }"
    >XXX详情页</router-link>
    
    js 跳转
    this.$router.push({
           path: `/goodsDetailTwo/${this.man.name}/${this.man.age}`
    });
    

    接收参数

    this.$route.params.XXXX
    

    二、组件传参

    2.1、常用的父子组件传参(props 、 $emit)

    父组件向子组件传参( props )

    第一步:在父组件引入子组件
    import SonOne from "./components/SonOne.vue"
    
    第二步:在components 注册子组件
    components: {
        SonOne
    },
    
    第三步:在 template 中使用子组件
    第四步:向子组件传参
    <SonOne :activity="{ id: '167368762886473', name: '套餐活动', productName: '电视TV 36寸' }"  />
    
    子组件 props 接收参数的方式 
    第一种数组方式
    props: [xxx, xxx, xxx]
    第二种对象方式
    props: { xxx: Number, xxx: String}
    第三种对象嵌套对象方式
    props: {
        xxx: {
            //类型不匹配会警告
            type: Number, String, Boolean 
            default: 0, "1", true
    
            type: Object, 接收的参数是 对象或数组,默认参数要用   default: () => 对象( {} )或 数组( [] )
            default: () => {},
            required: true,//是否必传
        }
    },
    
    第四步 props 接收父组件传过来的参数
    props: {
        activity: {
            type: Object,
            default: () => {},
            required: true,
        }
    },
    

    子组件向父组件传参( $emit )

    第一步:在父组件添加自定义事件  @notice
    <SonOne :activity="{ id: '167368762886473', name: '套餐活动', productName: '电视TV 36寸' }" @notice="notice" />
    
    第二步:子组件调用 $emit 方法,第一个参数就是父组件定义的自定义事件,第二个参数是子组件传给父组件的值
    this.$emit("notice", { id: "167368762886473", name: "修改后的套餐", productName: "修改后的产品" })
    

    2.2、父子组件传参,通过父链 / 子链也可以通信($parent / $children

    • this.$parent 可以直接访问该组件的父实例或组件
    • 父组件也可以通过 this.$children 访问它所有的子组件。

    \color{red}{需要注意: 数据不是响应式的}

    2.2.1、在子组件中用$children.调用父组件的方法或获得其数据
    this.$children.属性
    this.$children.方法
    第一步:在父组件引入子组件
    import SonTwo from "./components/SonTwo.vue"
    
    第二步:在components 注册子组件
    components: {
        SonTwo
    },
    
    第三步:在 template 中使用子组件
    <SonTwo />
    <van-button type="info" @click="callSon">调用 $children</van-button>
    
    data() {
        return {
            //tempSonData: {name: "baobao", age: 22},
            name: "父组件"
        };
    },
    
    第四步:父组件按调用子组件 noticeSon 方法,访问子组件的 num 属性
    callSon(){
        console.log(this.$children);//this.$children 访问当前组件的所有的子组件,是个数组
        console.log(this.$children[1].num);//获取子组件的 num 属性
        this.$children[1].noticeSon(this.name);//调用子组件的 noticeSon 方法并传参
    },
    
    第五步:子组件定义父组件调用的方法和访问的属性
    data() {
        return {
            parentData: null,
            num: 10,
        };
    },
    
    noticeSon(val){
          this.parentData = val
    },
    
    2.2.2、在子组件中用$parent.调用父组件的方法或获得其数据
    this.$parent.属性
    this.$parent.方法
    第一步:在 template 中触发事件
    <van-button @click="parentEvent" type="info">调用 $parent</van-button>
    
    第二步:子组件调用父组件 callSon 方法,访问父组件的 name 属性
    parentEvent(){
        console.log(this.$parent.name)
        this.$parent.calledSon(this.tempParentData)
    },
    
    第三步:父组件定义子组件调用的方法
    data() {
        return {
            sonData: null,
            name: "父组件"
        };
    },
    
    calledSon(val){
        this.sonData = val
    },
    

    2.3、组件传参,通过 eventBus 中央事件总线 (常用于 兄弟组件,跨父子组件)

    公共事件总线 eventBus 的实质就是创建一个 vue 实例,通过一个空的 vue 实例作为桥梁实现vue组件间的通信。它是实现非父子组件通信的一种解决方案。
    创建一个 vue-bus 插件, 使用中央事件总线
    
    第一步:在 utils 文件中创建 vue-bus.js 文件
    const install = function (Vue) {
        const Bus = new Vue({
            methods: {
                emit (event, ...args) {
                    this.$emit(event, ...args);
                },
                on (event, callback) {
                    this.$on(event, callback);
                },
                off (event, callback) {
                    this.$off(event, callback);
                }
            }
        });
        Vue.prototype.$bus = Bus;
    };
    
    export default install;
    
    第二步:在 main.js 中使用插件:
    import VueBus from './vue-bus' ;
    Vue.use(VueBus);
    
    第三步:A 组件向 B组件传参
    this.$bus.emit('add', "1111");
    
    第四步:B组件接收 A组件传递的参
    created() {
        this.$bus.on("add", this.addFunc);
      },
    

    第一是 $bus.on应该在 created钩子内使用,如果在 mounted使用,它可能接受不到其他组件来自created钩子发出的事件;
    第二点是使用了$bus.on,在beforeDestroy钩子里应该使用$bus.off解除,既然eventBus不会随着组件的销毁而注销事件, 所以应该去注销掉事件。

    beforedestroy() {
        this.$$bus.off("add");
      },
    

    相关文章

      网友评论

          本文标题:vue传参

          本文链接:https://www.haomeiwen.com/subject/vubjtrtx.html