父组件、子组件和兄弟组件定义以及相互调用
最近整理了一下vue写的代码,把四千多行的代码,整理成了三千多行,并且拆分了多个组件,用来进行公共调用。
下面就是一个业务层级的一个目录层级,在最外层是相当于父组件,里面的相当于子组件。
在main.js里面进行将组件注册成全局组件,方便调用,只需要填写如下代码,用来组件的初始化。testOne和testChildren就相当于兄弟组件。
import app_testChildren from './components/test/template/children/testChildren'
Vue.component('APP_TESTCHILDREN',app_testChildren)
import app_testOne from './components/test/template/one/testOne'
Vue.component('APP_TESTONE',app_testOne)
在父组件里面直接写上子组件加入传参,就可以实现父组件传参子组件的效果,在子组件里面定义一些属性,用来接住父组件的传参数据。test.vue代码。 ref 用来定义子组件变量,用来实现父组件调用子组件方法,而@方法名称,是为了,子组件调用父组件方法。
<template>
<div style="margin-top: 15rem">
<!--<p>-->
<!--<router-link to="/">test</router-link>-->
<!--<router-link to="/test/testChildren">test child</router-link>-->
<!--<router-link to="/test/testOne">test one</router-link>-->
<!--</p>-->
<!--<router-view></router-view>-->
<button @click="testToTestCildren" type="button">父组件调用子组件的方法</button>
<APP_TESTCHILDREN
:testChildrenNumber="testChildrenNumber"
:testChildrenObj="testChildrenObj"
:testChildrenType="testChildrenType"
ref="testChildrenInfo"
@testChildrenClick="testChildrenClick"
>
</APP_TESTCHILDREN>
</div>
</template>
<script>
export default {
name: 'test',
data () {
return {
testChildrenNumber: 1,
testChildrenObj: {},
testChildrenType: 'test to testChildren'
}
},
methods: {
testChildrenClick (obj) {
console.log(obj);
console.log('子组件 调用 父组件的方法')
},
testToTestCildren(){
this.$refs.testChildrenInfo.testFunction({"test":"父组件调用子组件方法"});
}
}
}
</script>
this.$emit('testChildrenClick', {row: 111, index: 222}),则是子组件调用父组件用来传参操作。testChildren.vue
<template>
<div style="margin-top: 15rem">
<h1 lastname="1223">welcome to test children page</h1>
<button @click="testChildrenToTest" type="button">子组件调用父组件的方法</button>
</div>
</template>
<script>
export default {
name: "testChildren",
props:{
testChildrenNumber:{
type:Number,
},
testChildrenObj:{
type:Object,
},
testChildrenType:{
type:String,
}
},
data() {
return {
}
},
methods:{
testFunction(obj){
console.log(obj)
},
testChildrenToTest(){
this.$emit('testChildrenClick', {row: 111, index: 222})
}
}
}
</script>
最后,父组件调用子组件,子组件也可以调用父组件,这样的话就可以实现兄弟组件之间的相互调用,传参以及组件加载。结果如下图所示。