Vue-CLIでProvide/Injectの使い方を学習してます。
以下動画サイトに基づいて、コーディングしたのですが'ChildC.vue'で定義した'childUserName'が表示されず行き詰まってます。
https://www.youtube.com/watch?v=VS7Qy0TYtN0
動画(4:16時点)では'childUserName'が'Codevolution'と表示されるはずなのですが、表示されません。
何が問題なのか全く分かりません。ご教授頂けないでしょうか?
vue
1// App.vue 2<template> 3 <div id="app"> 4 <ProvideInject /> 5 </div> 6</template> 7 8<script> 9import ProvideInject from './components/ProvideInject.vue' 10export default { 11 name: 'App', 12 components: { 13 ProvideInject, 14 }, 15} 16</script>
vue
1// components/ProvideInject.vue 2<template> 3 <div> 4 <h3>Parent component {{ name }}</h3> 5 <ChildA /> 6 </div> 7</template> 8 9<script> 10import { provide } from 'vue' 11import ChildA from './ChildA.vue' 12export default { 13 components: { ChildA }, 14 name: 'ProvideInject', 15 setup() { 16 provide('c_userName', 'Codevolution') 17 }, 18 data() { 19 return { 20 name: 'Vishwas', 21 } 22 }, 23 provide() { 24 return { 25 userName: this.name, 26 } 27 }, 28} 29</script>
vue
1// components/ChildA.vue 2<template> 3 <div> 4 <h2>Child Component A</h2> 5 <ChildB /> 6 </div> 7</template> 8 9<script> 10import ChildB from './ChildB' 11export default { 12 name: 'ChildA', 13 components: { 14 ChildB, 15 }, 16} 17</script>
vue
1//components/ChildB.vue 2<template> 3 <div> 4 <h2>Child Component B</h2> 5 <ChildC /> 6 </div> 7</template> 8 9<script> 10import ChildC from './ChildC' 11export default { 12 name: 'ChildB', 13 components: { 14 ChildC, 15 }, 16} 17</script>
vue
1// components/ChildC.vue 2<template> 3 <div> 4 <h2>Child Component C</h2> 5 <h3>Child Component C username - {{ userName }}</h3> 6 <h3>Child Component C composition username - {{ childUserName }}</h3> 7 </div> 8</template> 9 10<script> 11import { inject } from 'vue' 12export default { 13 name: 'ChildC', 14 setup() { 15 const childUserName = inject('c_userName', 'Default username') 16 return { 17 childUserName, 18 } 19 }, 20 inject: ['userName'], 21} 22</script>
《補足》
consoleでのエラーメッセージは以下の通り出ております。
vue.runtime.esm.js?2b0e:619 [Vue warn]: Property or method "childUserName" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
found in
---> <ChildC> at src/components/ChildC.vue
<ChildB> at src/components/ChildB.vue
<ChildA> at src/components/ChildA.vue
<ProvideInject> at src/components/ProvideInject.vue
<App> at src/App.vue
<Root>
あなたの回答
tips
プレビュー