我是Vue.js的初学者,所以请多多包涵。我创建了两个子组件和一个父组件。我能够在父组件中加载两个组件。现在,默认情况下,我的子组件之一应加载到父组件中。它将具有一个链接,并且单击该链接时,应通过将ID值从其自身传递到加载组件来将同一父组件中的另一个子组件加载。下面是我的代码。
父组件(App.vue):
<template>
<div id="app">
<body>
<main>
<div class="main-body">
<component v-bind:is="currentComp">
</component>
</div>
</main>
</body>
</div>
</template>
<script>
import HomeContent from './components/HomeContent.vue';
import DetailContent from './components/DetailContent.vue';
import { changeRoute } from './main.js';
export default {
name: 'app',
data() {
return {
currentComp: 'HomeContent'
};
},
components: {
HomeContent, //this is the default child component
DetailContent, //this is the other child component which should get loaded dynamically
},
created() {
changeRoute.$on('switchComp', comp => {
this.currentComp = comp;
})
}
}
</script>
默认子组件(HomeContent.vue):
<template>
<div>
This is Default child component
<a href="javascript:void(0);" @click="switchComponent('DetailContent')">Click to load the other child dynamically</a>
</div>
</template>
<script>
import { changeRoute } from '../main.js';
export default {
name: 'HomeContent',
props: {
msg: String
},
methods: {
switchComponent(comp) {
changeRoute.$emit('switchComp', comp);
}
}
}
</script>
另一个子组件(DetailContent):
<template>
<div>
This is the other loaded child component.
</div>
</template>
<script>
export default {
name: 'DetailContent',
props: {
msg: String
},
mounted(){
alert('mount ok');
}
}
</script>
通过上述方法,DetailContent
会在点击HomeContent
中的链接后加载。现在,如何将某些数据(例如ID = 1)从HomeContent
传递到DetailContent
。请帮忙吗?