我在 Vue.js 中有一个父组件,如下所示:
<template>
<ul class="list-group">
<li class="list-group-item" v-for="item in items">
<div class="row">
<div class="col-md-6">
{{ item.title }}
</div>
<div class="col-md-6 text-right">
<a href="#" class="btn btn-primary btn-sm">
<span class="glyphicon glyphicon-pencil"></span>
</a>
<a href="#" class="btn btn-success btn-sm">
<span class="glyphicon glyphicon-link"></span>
</a>
<a href="#" class="btn btn-danger btn-sm">
<span class="glyphicon glyphicon-remove"></span>
</a>
</div>
<div class="col-md-12">
<preview></preview>
</div>
</div>
</li>
</ul>
</template>
脚本:
<script>
import Preview from './Preview.vue';
export default {
data() {
return {
items: '',
template: []
}
},
created() {
this.fetchItems();
this.$on('preview-build', function (child) {
console.log('new preview: ')
console.log(child)
})
},
components: {
Preview
},
methods: {
fetchItems: function () {
var resource = this.$resource('api/preview');
resource.get({}).then((response) => {
this.items = response.body.item;
}, (response) => {
console.log('Error fetching tasks');
}).bind(this);
},
}
}
</script>
子组件“preview”具有类似模板的结构,例如 {{ item.title }}
。预览已正确加载,但未呈现。
我真的不知道在 Vue 2.0 中是否可行,但希望有人遇到同样的问题并能在这里帮助我。
编辑(感谢帕特里克):
<template>
<textarea rows="20" class="form-control">
{{ template.content }}
</textarea>
</template>
<script>
export default {
data() {
return {
template: [],
}
},
created() {
this.fetchTemplate();
},
methods: {
fetchTemplate: function () {
var resource = this.$resource('api/preview');
resource.get({}).then((response) => {
this.template = response.body.template;
}, (response) => {
console.log('Error fetching template');
}).bind(this);
},
}
}
</script>
这是类似于 Item.vue 内容的 Preview.vue 内容。 作为一个小解释:
模板数据来自数据库作为预定义的 html 内容,包括 {{ item.title }}
和其他一些占位符。我希望使用来自该项目的特定内容来呈现它。
最佳答案
在 Vue.js 中,组件无法直接从其父组件访问数据。如果你想要preview
能够呈现 {{ item.title }}
, 你必须通过 item
归结为 prop .所以在 preview.vue
,这样声明:
export default {
...
props: ['item']
}
然后,在父组件的模板中,您可以 v-bind
那item
支持来自 parent 的东西 items
数组:
<li class="list-group-item" v-for="item in items">
...
<preview v-bind:item="item"></preview>
...
</li>
现在您的 preview
组件有一个 item
它可以在其模板中呈现,就好像它是 data
的一部分一样对象。
关于javascript - Vue.js 使用父数据渲染子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39978672/