vue組件之間互相傳值:父傳子、子傳父

1、父組件向子組件傳值vue

1.建立子組件,在src/components/文件夾下新建一個child.vueless

2.在child.vue 中建立props,而後新加一個title屬性函數

<template>
	<div>
		<h1>child子組件</h1>
		<div>{{title}}</div>
	</div>
</template>
<script>
export default {
  name: 'child',
  props:["title"],
}
</script>
<style scoped lang="less">

</style>

3.在parent.vue父組件中註冊child組件,並在template中加入child標籤,標籤中綁定title屬性,並在data中賦值this

<template>
	<div>
		<h1>parent父組件</h1>
		<child v-bind:title="parentTitle"></child>
	</div>
</template>
<script>
import child from './child';//引用子組件
export default {
  name: 'parent',
  data(){
	  return {
		  parentTitle:"hello,child"
	  }
  },
  components:{
	  child
  }
}
</script>
<style scoped lang="less">

</style>

父組件向子組件傳值總結:code

  • 子組件在props中建立一個屬性,用以接收父組件傳過來的值
  • 父組件中註冊子組件
  • 在子組件標籤中添加子組件props中建立的屬性
  • 把須要傳給子組件的值賦給該屬性

2、子組件向父組件傳值component

1.在子組件中建立一個按鈕,給按鈕綁定一個點擊事件事件

2.在響應該點擊事件的函數中使用$emit來觸發一個自定義事件,並傳遞一個參數ip

<template>
	<div>
		<h1>child子組件</h1>
		<button @click="sendMsgToParent">向父組件傳值</button>
	</div>
</template>
<script>
export default {
  name: 'child',
  methods:{
	  sendMsgToParent(){
		  this.$emit("listenToChildEvent","this message is from child")
	  }
  }
}
</script>
<style scoped lang="less">

</style>

3..在父組件中的子標籤中監聽該自定義事件並添加一個響應該事件的處理方法it

<template>
	<div>
		<h1>parent父組件</h1>
		<child v-on:listenToChildEvent="showMsgFromChild"></child>
	</div>
</template>
<script>
import child from './child';//引用子組件
export default {
  name: 'parent',
  data(){
  },
  components:{
	  child
  },
  methods:{
	  showMsgFromChild(msg){
		  console.log(msg)
	  }
  }
}
</script>
<style scoped lang="less">

</style>

子組件向父組件傳值總結:console

  • 子組件中須要以某種方式例如點擊事件的方法來觸發一個自定義事件
  • 將須要傳的值做爲$emit的第二個參數,該值將做爲實參傳給響應自定義事件的方法
  • 在父組件中註冊子組件並在子組件標籤上綁定對自定義事件的監聽

總之,在通訊中,不管是子組件向父組件傳值仍是父組件向子組件傳值,他們都有一個共同點就是有中間介質,子向父的介質是自定義事件,父向子的介質是props中的屬性。

相關文章
相關標籤/搜索