日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 前端技术 > vue >内容正文

vue

Vue之组件之间的数据传递

發(fā)布時(shí)間:2023/12/19 vue 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Vue之组件之间的数据传递 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Vue的組件作用域都是孤立的,不允許在子組件的模板內(nèi)直接引用父組件的數(shù)據(jù),必須使用特定的方法才能實(shí)現(xiàn)組件之間的數(shù)據(jù)傳遞。

下列為在vue-cli創(chuàng)建項(xiàng)目中的操作

一·父組件向子組件傳遞數(shù)據(jù)

在Vue中,用props向子組件傳遞數(shù)據(jù)。

子組件部分:
1 <template> 2 <div class='header'>{{logo}}</div> 5 </template> 6 <script> 7 export default{ 8 name:"headerDiv", 9 data(){ 10 return { 11 ............ 12 } 13 }, 14 props:["logo"] 15 } 16 </script>?

如果需要從父組件獲取logo值,就需要使用props:['logo']

在props中添加了元素之后,就不需要在data中再添加變量了

父組件部分:

1 <template> 2 <div id='app'> 3 <HeaderDiv :logo="logoMsg"></HeaderDiv> 4 </div> 5 </template> 6 <script> 7 import HeaderDiv from './compontents/header' 8 9 export default{ 10 name:'app', 11 data(){ 12 return { 13 logoMsg:'VUE' 14 } 15 }, 16 components:{ 17 HeaderDiv 18 } 19 } 20 </script>

?二·子組件向父組件傳遞數(shù)據(jù)

子組件主要通過(guò)事件傳遞數(shù)據(jù)給父組件

子組件部分:

1 <template> 2 <div class='header'> 3 <input v-model="name" @change="getCh"> 4 </div> 5 </template> 6 <script> 7 export default { 8 name:'header', 9 data(){ 10 return { 11 name:'' 12 } 13 }, 14 methods:{ 15 getCh:function(){ 16 this.$emit('setCh',this.name) 17 } 18 } 19 } 20 </script>

當(dāng)name變化時(shí),將name傳給父組件,

在getCh中用$emit來(lái)遍歷setCh事件,并返回this.name

setCh是一個(gè)自定義事件,this.name通過(guò)該事件傳遞給父組件

父組件部分:

<template><div id='app'><HeaderDiv @trans='getCh'></HeaderDiv><div>{{user}}</div></div> </template> <script>import HeaderDiv from './components/header'export default {name:'app',data(){return {name:''}},methods:{getCh(msg){this.name=msg}},components:{HeaderDiv}} </script>

?三·子組件互相傳值

1.在main.js里全局定義eventBus

2.firstchild.vue

<template><div><button @click="btn">我是子組件一</button></div> </template> <style type="text/css"></style> <script type="text/javascript">export default{name:'Firstchild',methods:{btn(){console.log('start');eventBus.$emit('name','hello')}}} </script>

3.secondchild.vue

<template><div><button @click="btn2">我是子組件二</button></div> </template> <style type="text/css"></style> <script type="text/javascript">export default{name:'Secondchild',methods:{btn2(){console.log('end');eventBus.$on('name',function(val){console.log('我是firstchild組件傳過(guò)來(lái)的'+val)})}}} </script>  

?運(yùn)行結(jié)果

?

轉(zhuǎn)載于:https://www.cnblogs.com/wdxue/p/7541672.html

總結(jié)

以上是生活随笔為你收集整理的Vue之组件之间的数据传递的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。