Vue.js 在Vue js中从父组件定义子组件的布局
我是Vue新手,使用的是Vue.js 在Vue js中从父组件定义子组件的布局,vue.js,vuejs2,vue-component,Vue.js,Vuejs2,Vue Component,我是Vue新手,使用的是Vue 2.2.1。我想知道是否有可能创建一个可重用组件,该组件的布局由其父级定义。例如,考虑下面的伪代码: // Parent template <template> <ul> <li v-for="item in items"> <item-component :id="item.id"> <h1><item-title /></h1>
Vue 2.2.1
。我想知道是否有可能创建一个可重用组件,该组件的布局由其父级定义。例如,考虑下面的伪代码:
// Parent template
<template>
<ul>
<li v-for="item in items">
<item-component :id="item.id">
<h1><item-title /></h1>
<p>
<item-description />
</p>
</item-component>
</li>
</ul>
</template>
// Child definition
<script>
export default {
data() {
return {
title: '',
description: ''
}
}
create() {
// do some async fetch
fetch(this.id)
.then((result) {
this.$data.title = result.title
this.$data.description = result.description
})
}
}
</script>
//父模板
-
//儿童定义
导出默认值{
数据(){
返回{
标题:“”,
说明:“”
}
}
创建(){
//做一些异步获取
获取(this.id)
.然后((结果){
这是。$data.title=result.title
这是。$data.description=result.description
})
}
}
因此,用例是子组件负责按id获取数据,而父组件负责布局数据。这样,我可以将获取逻辑保留在一个地方,但可以在不同的地方以我想要的方式重新格式化数据
不确定这是否可行。我想我可以将孩子的抓取功能提取到mixin中,但是接下来我必须为每个布局变体创建一个新组件。在Vue中处理此问题的推荐方法是什么?通常,当您希望父级在子级中包含内容时,可以通过。然而,在一个典型的插槽内部,作用域是父级的作用域,这意味着它不能访问子级内部的数据 在您的情况下,您可能希望使用,在这里,孩子可以将一些信息传递回家长使用
// Parent template
<template>
<ul>
<li v-for="item in items">
<item-component :id="item.id">
<template scope="props">
<h1>{{props.title}}</h1>
<p>
{{props.description}}
</p>
</template>
</item-component>
</li>
</ul>
</template>
// Child definition
<script>
export default {
template:"<div><slot :title='title' :description='description'></slot></div>",
data() {
return {
title: '',
description: ''
}
}
create() {
// do some async fetch
fetch(this.id)
.then((result) {
this.$data.title = result.title
this.$data.description = result.description
})
}
}
</script>
//父模板
-
{{props.title}
{{props.description}
//儿童定义
导出默认值{
模板:“”,
数据(){
返回{
标题:“”,
说明:“”
}
}
创建(){
//做一些异步获取
获取(this.id)
.然后((结果){
这是。$data.title=result.title
这是。$data.description=result.description
})
}
}
一般来说,当您希望父对象在子对象中包含内容时,可以通过。然而,在一个典型的插槽内部,作用域是父级的作用域,这意味着它不能访问子级内部的数据
在您的情况下,您可能希望使用,在这里,孩子可以将一些信息传递回家长使用
// Parent template
<template>
<ul>
<li v-for="item in items">
<item-component :id="item.id">
<template scope="props">
<h1>{{props.title}}</h1>
<p>
{{props.description}}
</p>
</template>
</item-component>
</li>
</ul>
</template>
// Child definition
<script>
export default {
template:"<div><slot :title='title' :description='description'></slot></div>",
data() {
return {
title: '',
description: ''
}
}
create() {
// do some async fetch
fetch(this.id)
.then((result) {
this.$data.title = result.title
this.$data.description = result.description
})
}
}
</script>
//父模板
-
{{props.title}
{{props.description}
//儿童定义
导出默认值{
模板:“”,
数据(){
返回{
标题:“”,
说明:“”
}
}
创建(){
//做一些异步获取
获取(this.id)
.然后((结果){
这是。$data.title=result.title
这是。$data.description=result.description
})
}
}
使用作用域插槽。使用作用域插槽。