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>

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM