Vue的組件作用域都是孤立的,不允許在子組件的模板內直接引用父組件的數據,必須使用特定的方法才能實現組件之間的數據傳遞。
下列為在vue-cli創建項目中的操作
一·父組件向子組件傳遞數據
在Vue中,用props向子組件傳遞數據。
子組件部分:
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>
?二·子組件向父組件傳遞數據
子組件主要通過事件傳遞數據給父組件
子組件部分:
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>
當name變化時,將name傳給父組件,
在getCh中用$emit來遍歷setCh事件,并返回this.name
setCh是一個自定義事件,this.name通過該事件傳遞給父組件
父組件部分:
<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組件傳過來的'+val)})}}}
</script>
?運行結果
?