最近在使用vue进行开发,遇到了组件之间传参的问题,此处主要是针对非父子组件之间的传参问题进行总结,方法以下:
1、若是两个组件用友共同的父组件,即vue
FatherComponent.vue代码 <template> <child-component1/> <child-component2/> </template> 此时须要组件1给组件2传递某些参数,实现以下:
一、父组件给组件1绑定一个方法,让组件1进行回调,组件2接收某个属性,经过改变父组件的数据从而实现组件2的属性值的更新,即
父组件vuex
<child-component1 :callback="child1Callback" /> <child-component2 :props="child2Props" /> data () { return { child2Props: ''; } } child1Callback ([args...]) { // 此处更新了父组件的data,使组件2的属性prop改变 this.child2Props = [args...] }
组件1学习
props: ['callback'] change () { this.callback([args...]) }
二、经过bus进行实现,首先bus.js以下this
const bus = new Vue() export default bus
组件1code
import bus from './bus' methods: { change () { bus.$emit('callComponent2', [args...]) } }
组件2component
import bus from './bus' mounted () { bus.$on('callComponent2', function ([args...]) { // 作你想作的 }) }
三、利用vuex实现,建立store.js至关于某些全局变量,可是能够被vue检测到变化开发
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { pageNo: 0 }, mutations: { 'change' (state, [args...]) { state.pageNo++ } } }) export default store
项目入口js文档
import store from './store.js' new Vue({ ... store: store ... })
此时在任意vue文件均可以改变pageNo的值,而且会影响到全部使用了pageNo的组件,都会进行更新
childComponent1.vueit
this.$store.commit('change')
childComponent2.vueio
{{this.$store.state.pageNo}}
总结: 一、第一种比较绕,须要有共同的父组件,若是组件间层级太多,会致使代码混乱,比较难维护。 二、第二种比较直观,推荐使用,可是要理解,请仔细阅读官方文档 三、利用vuex在不少项目中都会显得杀鸡用牛刀,虽然更好理解,可是也带来了学习成本,而且可能会有一些反作用,可是若是项目比较复杂,利用vuex更加直观综合各类方法的优缺点,推荐使用第二种,项目过于复杂请使用第三种若是有更好的方法,请留言指教,谢谢