Vue之组件之间的数据传递
生活随笔
收集整理的這篇文章主要介紹了
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)題。
- 上一篇: HAProxy用法详解 全网最详细中文文
- 下一篇: vue设置多选框默认勾选_Angular