iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 12
1
Modern Web

超緊繃!30天Vue.js學習日記系列 第 12

[Vue.js][日記]父與子的敲敲話...

https://ithelp.ithome.com.tw/upload/images/20190912/20110850dsypfXRkNe.jpg

超緊繃!30天Vue.js學習日記 父與子的敲敲話

大家好,我Ian啦!,今天要介紹的是組件中非常重要的選項(option)-props,它是用於父子組件間的溝通(單向:父傳給子),因為子組件的模板與模組無法直接使用父組件的數據,因此需要通過props將父組件的數據傳遞給子組件,子組件在接收數據時需要聲明props,範例如下:

<div id="app">
<my-component x='123' y='456'>
</my-component>
</div>
<script>
Vue.component('my-component',{
  props:['x','y'],
  template:'<h1>{{x+y}}</h1>'
});
new Vue({
  el:'#app'
});
</script>

在範例中,props是一個陣列,我們在這邊定義由x以及y接收數據,再將它們印出來。

對了,在這邊再次提醒大家,我們的全域組件一定要註冊在根實例之前喔!!!

同樣的,我們可以使用v-bind動態綁定props:

<div id="app2">
<my-component2 :status="text"></my-component2>
</div>
<script>
Vue.component('my-component2',{
  props:['status'],
  template:'<h1>{{status}}</h1>'
});
new Vue({
  el:'#app2',
  data:{
  	text:'hello!world!'
  }
});
</script>

我們在這邊使用status去接球,並且將資料綁定text後傳值。

若我們想要一次傳多個數據過去呢?可以搭配v-for使用:

<div id="app3">
	<my-component3 v-for="str in arr" :status="str"></my-component3>
</div>
<script>
Vue.component('my-component3',{
  props:['status'],
  template:'<h1>{{status}}</h1>'
});
new Vue({
  el:'#app3',
  data:{
  	arr:['123','456','789']
  }
});
</script>

當data為物件時,我們一樣能夠進行傳遞:

<div id="app4">
	<my-component4 v-for="str in obj" :status="str"></my-component4>
</div>
<script>
Vue.component('my-component4',{
  props:['status'],
  template:'<h1>{{status.id}}:{{status.name}}</h1>'
});
new Vue({
  el:'#app4',
  data:{
  	obj:[
  	  {name:"ian", id:"1"},
      {name:"tracy", id:"2"}
  	]
  }
});
</script>

今天的最後,我們來試試看使用input box去傳值給子組件 :

<div id="app5">
	<form>
		<input @change="update" v-model="name2" type="text" >
	</form>
	<my-component5 :cname="name"></my-component5>
</div>
<script>
Vue.component('my-component5',{
  props:['cname'],
  template:'<h1>{{cname}}</h1>'
});
new Vue({
	el:'#app5',
	data:{
		name:"123",
		name2:""
	},
	methods:{
		update(){
			let vm = this;
			vm.name = vm.name2; //更新name的值(要傳的值)
			//console.log(vm.name , vm.name2);
		}
	}
})
</script>

本日範例下載:

https://drive.google.com/open?id=1y7IDeEdLwQ_IeWYgQRKr0b0m4V7S0u5C

感謝各位的收看,我們明天見!


上一篇
[Vue.js][日記]我還要更多!組件的相關補充
下一篇
[Vue.js][日記]父與子的敲敲話...(2)
系列文
超緊繃!30天Vue.js學習日記33
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言