2_Vue中组件通信的几种方式
1、props
功能:让组件接收外部传过来的数据,可用于父子组件之间的通信
备注:props是只读的,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求确实需要修改,那么请复制props的内容到data中一份,然后去修改data中的数据。
1 //简单声明接收 2 // props:['name','age','sex'] 3 4 //接收的同时对数据进行类型限制 5 /* props:{ 6 name:String, 7 age:Number, 8 sex:String 9 } */ 10 11 //接收的同时对数据:进行类型限制+默认值的指定+必要性的限制 12 props:{ 13 name:{ 14 type:String, //name的类型是字符串 15 required:true, //name是必要的 16 }, 17 age:{ 18 type:Number, 19 default:99 //默认值 20 }, 21 sex:{ 22 type:String, 23 required:true 24 } 25 } 26 }
2、组件的自定义事件
-
-
使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中
1 父组件中: 2 <Category> 3 <div>html结构1</div> 4 </Category> 5 子组件中: 6 <template> 7 <div> 8 <!-- 定义插槽 --> 9 <slot>插槽默认内容...</slot> 10 </div> 11 </template>
3.2具名插槽
1 父组件中: 2 <Category> 3 <template slot="center"> 4 <div>html结构1</div> 5 </template> 6 7 <template v-slot:footer> 8 <div>html结构2</div> 9 </template> 10 </Category> 11 子组件中: 12 <template> 13 <div> 14 <!-- 定义插槽 --> 15 <slot name="center">插槽默认内容...</slot> 16 <slot name="footer">插槽默认内容...</slot> 17 </div> 18 </template>
3.3作用域插槽
1 父组件中: 2 <Category> 3 <template scope="scopeData"> 4 <!-- 生成的是ul列表 --> 5 <ul> 6 <li v-for="g in scopeData.games" :key="g">{{g}}</li> 7 </ul> 8 </template> 9 </Category> 10 11 <Category> 12 <template slot-scope="scopeData"> 13 <!-- 生成的是h4标题 --> 14 <h4 v-for="g in scopeData.games" :key="g">{{g}}</h4> 15 </template> 16 </Category> 17 子组件中: 18 <template> 19 <div> 20 <slot :games="games"></slot> 21 </div> 22 </template> 23 24 <script> 25 export default { 26 name:'Category', 27 props:['title'], 28 //数据在子组件自身 29 data() { 30 return { 31 games:['红色警戒','穿越火线','劲舞团','超级玛丽'] 32 } 33 }, 34 } 35 </script>
1 new Vue({ 2 ...... 3 beforeCreate() { 4 Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm 5 }, 6 ...... 7 })
使用事件总线:
1 //接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身。 2 methods(){ 3 demo(data){......} 4 } 5 ...... 6 mounted() { 7 this.$bus.$on('xxxx',this.demo) 8 } 9 //提供数据: 10 this.$bus.$emit('xxxx',数据)
优化:最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件。
5、消息订阅与发布(不用)
6、Vuex(vue开发必用)
使用场景:多个组件需要共享数据时
在Vue中实现集中式状态(数据)管理的一个Vue插件,对vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信。
设计程序时经常向服务器请求数据
1 //引入Vue核心库 2 import Vue from 'vue' 3 //引入Vuex 4 import Vuex from 'vuex' 5 //引用Vuex 6 Vue.use(Vuex) 7 8 const actions = { 9 //响应组件中加的动作 10 jia(context,value){ 11 // console.log('actions中的jia被调用了',miniStore,value) 12 context.commit('JIA',value) 13 }, 14 } 15 16 const mutations = { 17 //执行加 18 JIA(state,value){ 19 // console.log('mutations中的JIA被调用了',state,value) 20 state.sum += value 21 } 22 } 23 24 //初始化数据 25 const state = { 26 sum:0 27 } 28 29 //当state中的数据需要经过加工后再使用时,可以使用getters加工 30 const getters = { 31 bigSum(state){ 32 return state.sum * 10 33 } 34 } 35 36 //创建并暴露store 37 export default new Vuex.Store({ 38 actions, 39 mutations, 40 state, 41 getters 42 })
组件中修改vuex中的数据:$store.dispatch('action中的方法名',数据) 或

浙公网安备 33010602011771号