Vue中的传值方式(父子传值,祖孙传值,兄弟传值,无关联组件传值)

参考: https://blog.csdn.net/qq_35430000/article/details/79291287

1.路由传参

  两页面要有路由跳转,在路由跳转的时候通过query把数据传给B组

1
this.$router.push({ path: '/conponentsB', query: { id: 123 } })

  在B组件获取传来的数据

1
this.$route.query.id

2.通过本地存储传递(sessionStorage,localStorage)

  sessionStorage使用需要在浏览器同一会话内,页签或者浏览器关闭都会删除.localStorage存储整个网站数据,无过期时间,直到手动删除.存储的数据为字符串

1
sessionStorage.setItem('TOKEN', token)

 获取数据

1
let token= sessionStorage.getItem("TOKEN");

3.父子组件传值

  a.父组件往子组件传值通过props

父组件传值

1
2
3
4
5
<template>
  <div id="app">
    <Demo :sonId="父组件给子组件传的值"></Demo>
  </div>
</template>

 子组件接收

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<template>
  <div>
    <h1>{{sonId}}</h1>
  </div>
</template>
<script>
  export default {
    props: {
      'sonId': String,
    },
    // props:['sonId'],
    // props: {
    //   sonId: {
    //     default: '',
    //     type: String
    //   }
    // },
    data() {
      return {}
    }
  }
</script>

  b.子组件往父组件传值 $emit

子组件触发传值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<template>
    <div>
        <div @click="sendParent"></div>
    </div>
</template>
<script>
export default {
    data(){
        return {}
    },
     methods:{
        sendParent(){
            this.$emit('sonSend','子组件给父组件的传值')
        }
    }
}
</script>

父组件接收

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<template>
  <div id="app">
    <Demo @sonSend="getSend"></Demo>
  </div>
</template>
<script>
export default {
    data(){
        return {}
    },
    methods:{
        getSend(val){
            console.log(val)
        }
    }
}
</script>

 通过父子组件的相互传值,还可以利用父组件的中转,实现兄弟组件传值

4.事件总线 evenBus

 创建.js文件 

1
2
3
// eventBus.js
import Vue from 'vue'
export const EventBus = new Vue()

 发送数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<template>
    <button @click="sendMsg()">-</button>
</template>
 
<script>
import { EventBus } from "../eventBus.js";
export default {
  methods: {
    sendMsg() {
      EventBus.$emit("AMsg", 'A页面消息');
    }
  }
};
</script>

接收消息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<template>
  <div>{{msg}}</div>
</template>
 
<script>
import {
  EventBus
} from "../eventbus.js";
export default {
  data(){
    return {
      msg: ''
    }
  },
  mounted() {
    EventBus.$on("AMsg", (msg) => {
      this.msg = msg;
    });
  }
};
</script>

  主要使用方法为:

// 发送消息
EventBus.$emit(channel: string, callback(payload1,…))

// 监听接收消息
EventBus.$on(channel: string, callback(payload1,…))

5.状态管理(vuex,pinia)

  vuex,pinia分篇来记载,vuex在vue2中使用较多适用于大型应用pinia在vue3成了官方建议用的状态管理,vue2也可以使用

  vuex: 

  pinia: https://www.cnblogs.com/foxing/p/15850585.html

6.inheritAttrs, arrtslistenter

  https://www.cnblogs.com/foxing/p/15879562.html

7. provide和inject (依赖注入)

  provide和inject一般一起使用,官网不建议在应用中直接使用该办法,数据追踪难度比较大.使用时在父组件只要声明了provide,在其子组件,孙组件,曾孙组件等能形成上下游关系的组件中交互,无论多深都能通过inject来访问provider中的数据。 

  provide:是一个对象,或者是一个返回对象的函数。包含传给子孙后代的东西,也就是属性和属性值。注意:子孙层的provide会掩盖祖父层provide中相同key的属性值

  inject:一个字符串数组,或者是一个对象。属性值可以是一个对象,包含fromdefault默认值,from是在可用的注入内容中搜索用的 key (字符串或 Symbol),意思就是祖父多层provide提供了很多数据,from属性指定取哪一个key;default指定默认值。

 父组件:

复制代码
<template>
  <div>
    <p>{{ title }}</p>
    <son></son>
  </div>
</template>
<script>
  import Son from "./son"
  export default {
    name: 'Father',
    components: { Son },

  // porvide:(){
  //   return {
  //     fatherData:this
  //   }
  // }

   provide: {
     message: '父组件提供信息'
   },

    data () {
      return {
        title: '父组件'
      }
    },
    methods: {  }
  }
</script>
复制代码

后代组件:

复制代码
<template>
  <div>
    <p>message:{{ message }}</p>
  </div>
</template>
<script>
export default {
  name: "SunSon",
  inject: ["message"],
//
inject: ["fatherData"],

// inject: ["fatherData"],

 // inject: {
 //   message: {
 //    from: 'message',
 //     default: '默认值'
 //   }
 // },

data () { return { title: '孙组件' } }, methods: { } }; </script>
复制代码

 

8. refparent

$ref可用于父组件调用子组件方法,变量

父组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<template>
    <div>
        <Demo ref="sonCom"></Demo>
        <button @click="getChildProp()">获取子组件的属性的值</button>
        <button @click="getChildMethod()">获取子组件的方法</button>
    </div>
</template>
<script>
import Demo from './demo.vue'
    export default{
        data(){
            return { }
        },
        components:{
           Demo
        },
        methods: {
          getChildProp(){
              alert(this.$refs.Demo.msg);
          }, 
          getChildMethod(){
              this.$refs.Demo.send();
          }
        },
    }
</script>
1
子组件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script>
    export default{
        data(){
            return {
                msg:"子组件demo的值"
            }
        },
        methods:{
            send(){
                console.log("子组件demo的方法")
            }
        }
    }
</script>

 $parent可用于子组件调用父组件方法,变量

父组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<template>
    <div>
        <Demo></Demo>
    </div>
</template>
<script>
import Demo from './demo.vue'
    export default{
        data(){
            return {
                msg:'父组件消息'
            }
        },
        components:{
           Demo
        },
        methods: {
         getMsg(){
              console.log(this.msg)
          }
        },
    }
</script>

子组件

1
2
3
4
5
6
7
8
9
10
<script>
    export default{
        data(){
            return { }
        },
        mounted:{
           this.$parent.getMsg
       }
    }
</script>
posted @   月下云生  阅读(572)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示