vue组件间的传值,父传子,子传父,兄弟之间传值,跨级传值

1.父传子

在vue中可以使用props向子组件传递数据
父组件内容

<template>
		<div id="app">
				<Child   :info="data">   </Child>
        </div>
</template>

在调用组件的时候,使用 v-bind 将 info的值绑定为 App.vue 中定义的变量 data

<script>
	import  Child  from "./components/child"
	export  default {
	   name:"app",
		data(){
			return{
			    data:"我是钱家寄"
			}
		},
		    components:{Child}
    }
</script>

子组件内容
如果要从子组件中获取到父组件中的值,需在子组件中写props[“info”]

<script>
    export default{
		name:'child',
		props:["info"]
   }
</script>

2.子传父

子组件主要通过事件传递数据给父组件
子组件内容

<template>
	<div>
	   <button @click="buggle">buggle</button>	
   </div>
</template>
<script>
	 data(){
		return{
		  username:"我是钱家寄"
		},
		methods:{
		  buggle(){
		     this.$emit("message",this.username)
		  }
		}
</script>

父组件内容

<template>
		<div>
				<Child @message="user"></Child>
		</div>
</template>
<script>
	import Child from "./componets/child.vue"
	export default{
		data(){
			return{
    			data:{}
    		}
		},
		components:{Child},
		methods:{
			user:function(val){
				this.data=val
			}
	   }		
	}
</script>

3.兄弟传值

第一种方式:先子传父,然后再父传子,需要注意的是使用props的时候,需要在computed中使用,监听数据变化。

第二种方式:借助中央事件总线bus.js
1.可以在assets文件夹下新建一个bus.js文件

import Vue from 'vue';
export default new Vue;

2.将2个组件做为子组件放入一个父组件中,在同一页面显示

<template>
<div>
		<b1></b1>
		<b2></b2>
</div>
</template>
<script>
import b1 from "./component/b1.vue"
import b2 from "./component/b2.vue"
export default {
   component:{
	  b1,b2
   }
}
</script>

3.在b1和b2组件中分别引入bus.js
b1组件

<script>
import Bus from 'bus.js' ;
export default {
  
  created() {
    // 在需要的传递数据的时候调用sendData方法,这里模拟调用
    this.sendData();
  },
  methods: {
    sendData () {
      Bus.$emit('listenToA', 'hello');
    }
  }
}
</script>

b2组件

<script>
import Bus from 'bus.js';
export default {
  name: "b",
  monted() {
    Bus.$on('listenToA', this.getAData);
  },
  methods: {
    getAData (val) {
      console.log(`a组件传递过来的数据: ${val}`); // hello
    }
  }
}
</script>

4.跨级传值

provider/inject
父组件:

//父组件示例

<template>
  <div>
    <childCom></childCom>
  </div>
</template>
<script>
  import childCom from '../components/childCom'
  export default {
    provide: {      //重要一步,在父组件中注入一个变量
      msg: "demo"
    },
    components:{
      childCom
    }
  }

子组件:

//子组件示例,这个不管嵌套了多少层,都能请求到父组件中注册的变量

<template>
  <div>
      {{msg}}
  </div>
</template>
<script>
  export default {
    name: "childCom",
    inject: ['msg'],//子孙组件中使用inject接住变量即可
  }
</script>
发布了25 篇原创文章 · 获赞 0 · 访问量 654

猜你喜欢

转载自blog.csdn.net/JamesHKK/article/details/103774817