vue-通信

1、props父子

1、Parent.vue

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
27
28
29
// Parent.vue
<template>
    <div>
        <span>我是Parent组件</span>
        <Child ref="child" :parentValue="value" @emitEdit="edit"></Child>
    </div>
</template>
<script>
import Child from "./Child.vue";
export default {
    components: { Child },
    data() {
        return {
            value: "我是父组件"
        }
    },
    methods: {
        pFn() {
            console.log("我是父组件的方法");
            // 调用子组件的方法
            this.$refs.child.cFn();
        },
        // 子组件触发,修改 value 的值
        edit(msg) {
            this.value = msg;
        }
    }
}
</script>

2、Child.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<template>
    <div>
        <span>我是Child组件</span>
        <span>父组件传的值:{{this.parentValue}}</span>
        <button @click="editParentValue">修改 parentValue</button>
    </div>
</template>
<script>
export default {
    props: {
        parentValue: String
    },
    methods: {
        cFn() {
            console.log("我是子组件的方法");
        }
        editParentValue() {
            this.$emit("emitEdit", "子组件修改了我");
        }
    }
}
</script>

 2、 $Bus全局变量

3、pubsub-js订阅与发布

4、-provide和inject

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
27
28
29
30
31
32
33
export default {
  name: 'App',
  data(){
    return{
      arr:["张三","李四","王五"],
      obj:{
        id:"001",
        num:80
      }
    }
  },
  /*
    1.函数返回对象的写法
    2.对象的写法,只能传递基本数据类型,
      如果传递对象、数组或方法,后代接收不到,需要使用函数返回对象的写法
  */
  provide(){
    return{
      arr:this.arr,
      obj:this.obj,
      getUserInfo:this.getUserInfo
    }
  },
  methods:{
    getUserInfo(e,value){
      console.log("获取用户信息",e.target,value);
    }
  },
  components: {
    HelloWorld,
    layout
  }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
<template lang="pug">
  .box
    ul
      li(v-for="i in arr", :key="i") {{ i }}
    a-button(@click="getUserInfo($event, 1000)")  点击调用getUserInfo函数
</template>
  
<script>
export default {
  name: "pug",
  inject: ["arr", "obj", "getUserInfo"],
};
</script>

5、vuex

6、parent/children类似第一种

 

posted @   小河池塘  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示