目錄
1:組件中的關系
2:父向子傳值
3:子組件向父組件共享數據
4:兄弟組件數據共享
1:組件中的關系
在項目中使用到的組件關系最常用兩種是,父子關系,兄弟關系
例如A組件使用B組件或者C組件或者BC組件都使用了,那么A組件就是BC組件的父,BC組件是A組件的子,BC組件就是兄弟關系。
2:父向子傳值
父子組件之間的數據共享
一個組件(父)中導入了兩外一個組件(子)使用自定義屬性,定義props在子組件中,共享數據
?在App.vue組件中使用Left組件,父組件向子組件傳值,在父組件中定義需要傳的數據,子組件中定義props接收父組件的數據
3:子組件向父組件共享數據
在子組件中通過$emit函數定義一個事件函數名稱和值,在父組件中聲明這個方法
?子組件示例代碼:
<template><div><div class="container"><span id="app">你好</span><span>計數:{{ count }}</span><button @click="add">+1</button></div></div>
</template><script>
export default {name: 'WORKSPACE_NAMEaa',props:['init'],data() {return {message:'Hello',count:1};},mounted() {console.info('tag', document.getElementById('app').style.color='red')},methods: {add(){this.count = this.count +1this.$emit('countchange', this.count);},show(){console.info('調用了show方法')}},created(){console.info(this.show)console.info(this.message)console.info(this.init)},updated(){},beforeUpdate(){}
};
</script><style lang="less" scoped>.container{background: goldenrod;width: 300px;height: 300px;border: 1px solid black}
</style>
父組件示例代碼:
<template><div><div class="footer_wrap"><router-link to="/find">發現音樂</router-link><router-link to="/my">我的音樂</router-link><router-link to="/friend">朋友</router-link></div><!-- <CCC init='你好' @countchange="getNewCount"></CCC></div>
</template><script>import testMyTag from '@/views/商品案例/MyTag.vue'
import testMyTable from '@/views/商品案例/MyTable.vue'
import houbeiMyDialog from '@/views/后備插槽/MyDialog.vue'
import MyDialog from '@/views/默認插槽/MyDialog.vue'
import MyTable from '@/views/作用域插槽/MyTable.vue'
import testMyDialog from '@/views/具名插槽/MyDialog.vue'
import testnexttick from '@/views/TestnextTick.vue'
import BaseFrom from '@/views/BaseFrom.vue'
import BaseChart from '@/views/BaseChart.vue'
import AAA from '@/views/Left.vue'
import BBB from '@/views/Right.vue'
import CCC from '@/views/aa.vue'
export default {// components:{// AAA,BBB,CCC,BaseChart,BaseFrom,testnexttick,testMyDialog,MyTable,MyDialog,houbeiMyDialog,testMyTag,testMyTable// },data(){return{countvalue:0}},methods: {getNewCount(val){this.countvalue = val}},
}
</script><style lang="less" scoped>
.footer_wrap a.router-link-exact-active{background-color: #007acc;
}
body {margin: 0px;
}
.footer_wrap {position: relative;left: 0;top: 0;display: flex;width: 100%;text-align: center;background-color: #333;color: #ccc;
}
.footer_wrap a {flex: 1;text-decoration: none;padding: 20px 0;line-height: 20px;background-color: #333;color: #ccc;border: 1px solid black;
}
.footer_wrap a:hover {background-color: #555;
}
</style>
4:兄弟組件數據共享
在vue2.x中,兄弟組件數據共享的方案EventBus
?