【发布时间】:2018-03-02 15:53:42
【问题描述】:
我正在尝试构建一个 VueJS 组件。我还有两个其他组件,我想以父子方式使用它们。现在,我想将父母的数据传递给孩子。是这样的:
App.vue
<template>
<div id="app">
<parent>
<child></child>
<child></child>
<child></child>
<child></child>
</parent>
</div>
</template>
<script>
import child from './child.vue'
import parent from './parent.vue'
var vm = new Vue({
el: '#app',
components: {
parent,
child
}
})
</script>
父.vue
<template>
<div class="container">
This is parent component
<slot>
</slot>
</div>
</template>
<script>
export default {
name: 'parent',
data () {
return {
parentMsg: {
'key1': 'value1',
'key2': 'value2'
}
}
}
}
</script>
child.vue
<template>
<div class="container">
Child component
<!-- I have to place a div here which will consume parentMsg object -->
<!-- Each instance of child component rendered should have access to parentMsg -->
<div>
<!-- Some HTML to consume the parentMsg -->
</div>
</div>
</template>
<script type="text/javascript">
export default {
name: 'child',
data () {
return {
demo: 'Demo message changed'
}
}
}
</script>
我希望parent.vue 中的parentMsg 可以在child.vue 中访问。我不想在App.vue 上暴露parentMsg。我怎样才能做到这一点?
我将使用 parentMsg 的div 放置在 parent.vue 模板中的未命名插槽内(以及之后),并认为对于 child.vue 的每个实例,都会呈现 div 的副本。它不起作用。
【问题讨论】:
-
为什么不将子组件放在父模板中,然后将消息从父模板传递给它们?插槽不适合这样使用。
标签: javascript vue.js vuejs2 vue-component