Vue组件传值,父传子,子传父,非父子组件
vue3中传值方式:
1、父组件向子组件传值
父组件Blog.vue
1 <template> 2 <div id="blog"> 3 <Alert v-if="alert" v-bind:message="alert"></Alert> 4 </div> 5 </template> 6 <script> 7 import Alert from './Alert' 8 export default { 9 name: 'blog', 10 data () { 11 return { 12 alert:'父组件向子组件传递的值' 13 } 14 }, 15 components:{ 16 Alert 17 } 18 } 19 </script>
子组件Alert.vue
1 <template> 2 <div class="alert"> 3 {{message}} 4 </div> 5 </template> 6 7 <script> 8 export default { 9 name: 'alert', 10 props:['message'], 11 data () { 12 return { 13 14 } 15 } 16 } 17 </script>
2、子组件向父组件传值
子组件child.vue
1 <template> 2 <div class="child"> 3 <input v-on:click="sendValue" type="button" value="子组件向父组件传值"> 4 </div> 5 </template> 6 <script> 7 export default{ 8 data(){ 9 return { 10 val:"子组件的value值" 11 } 12 }, 13 methods:{ 14 sendValue(){ 15 this.$emit('titleChanged',this.val); 16 } 17 } 18 } 19 </script>
titleChanged是父组件中绑定的函数名
父组件father.vue
1 <template> 2 <div class="father"> 3 <h1>{{faval}}</h1> 4 <child v-on:titleChanged="getValue"></child> 5 </div> 6 </template> 7 <script> 8 import child from './child.vue' 9 export default{ 10 data(){ 11 return { 12 faval:"Hello word!" 13 } 14 }, 15 components:{ 16 child 17 }, 18 methods:{ 19 getValue(data){ 20 this.faval = data 21 console.log(this.faval) 22 } 23 } 24 } 25 </script>
3、非父子组件传递值
非父子组件之间传值,需要定义工具文件eventHub.js进行传值,不然路由组件之间达不到传值的效果
组件之间传递参数工具类eventHub.js
1 import Vue from 'vue' 2 3 export default new Vue()
组件A向组件B传值
组件A.vue
1 <template> 2 <div class="classA"> 3 <input type="button" value="A组件向B组件发送值" v-on:click="returnHome"> 4 </div> 5 </template> 6 <script> 7 import Hub from './eventHub.js' 8 export default{ 9 data(){ 10 return { 11 msg:4 12 } 13 }, 14 methods:{ 15 returnHome(){ 16 Hub.$emit('val',this.msg) 17 } 18 } 19 } 20 </script>
组件B.vue
1 <template> 2 <div class="classB"> 3 <h3>{{name}}</h3> 4 </div> 5 </template> 6 <script> 7 import Hub from './eventHub.js' 8 export default{ 9 data(){ 10 return { 11 name:'' 12 } 13 }, 14 mounted:function(){ 15 var that = this 16 Hub.$on('val',(data)=>{ 17 that.name = data 18 }) 19 } 20 } 21 </script>