首页 > 其他分享 >vue-通信

vue-通信

时间:2022-08-29 17:56:09浏览次数:41  
标签:getUserInfo vue arr 通信 value Child 组件

1、props父子

1、Parent.vue

// 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

<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

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
  }
}

  

<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类似第一种

 

标签:getUserInfo,vue,arr,通信,value,Child,组件
From: https://www.cnblogs.com/xhct/p/16636780.html

相关文章