teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

回答の変更

2021/02/03 23:31

投稿

Twoshi
Twoshi

スコア354

answer CHANGED
@@ -7,21 +7,19 @@
7
7
  ```vue
8
8
  <template>
9
9
  <div id="app">
10
- <div class="hoge" :style="{ background: color}">親</div> // colorを元に色を設定
10
+ <div class="hoge" :style="{ background: color}">親</div>
11
- <FirstComponent @onClick="changeColor"/> // color変更処理を渡す
11
+ <FirstComponent @onClick="changeColor" :color="color"/>
12
- <SecondComponent :color="color"/> // colorを渡す
12
+ <FirstComponent @onClick="changeColor" :color="color"/>
13
13
  </div>
14
14
  </template>
15
15
 
16
16
  <script>
17
17
  import FirstComponent from './components/FirstComponent.vue'
18
- import SecondComponent from './components/SecondComponent.vue'
19
18
 
20
19
  export default {
21
20
  name: 'App',
22
21
  components: {
23
- FirstComponent,
22
+ FirstComponent
24
- SecondComponent
25
23
  },
26
24
  data: function() {
27
25
  return {
@@ -41,17 +39,16 @@
41
39
  width: 200px;
42
40
  }
43
41
  </style>
44
-
45
42
  ```
46
43
 
47
- 親から渡されたcolor変更処理と子1が持つmyColor変更処理を記載
44
+ 親から渡されたcolor変更処理を記載
48
- 入力ボタン押下で色変更をしたかったので、入力用(inputColor)と表示用(myColor)分けていま
45
+ 表示に利用るcolorは親から取得する
49
46
 
50
- 1
47
+
51
48
  ```vue
52
49
  <template>
53
50
  <div>
54
- <div class="hoge" :style="{background: myColor}">子1</div>
51
+ <div class="hoge" :style="{background: color}">子1</div>
55
52
  <input type="text" v-model="inputColor">
56
53
  <button type="button" @click="changeColor">入力</button>
57
54
  </div>
@@ -60,15 +57,14 @@
60
57
  <script>
61
58
  export default {
62
59
  name: 'FirstComponet',
60
+ props: ['color'],
63
61
  data: function() {
64
62
  return {
65
- myColor: '',
66
63
  inputColor: ''
67
64
  }
68
65
  },
69
66
  methods: {
70
67
  changeColor: function() {
71
- this.myColor = this.inputColor;
72
68
  this.$emit('onClick', this.inputColor);
73
69
  }
74
70
  }
@@ -81,28 +77,4 @@
81
77
  }
82
78
  </style>
83
79
  ```
84
-
85
- 受け取ったcolorを元に子2が持つdivタグの色をつけています。
86
- 子2
87
- ```vue
88
- <template>
89
- <div>
90
- <div class="hoge" :style="{background: color}">子2</div>
91
- </div>
92
- </template>
93
-
94
- <script>
95
- export default {
96
- name: 'SecondComponet',
97
- props: ['color']
98
- }
99
- </script>
100
-
101
- <style scoped>
102
- .hoge {
103
- width: 200px;
104
- }
105
- </style>
106
- ```
107
-
108
80
  ご参考になれば幸いです。