我是 Vue.js 的初学者,我想使用组件。我有一个(动态)表,其中包含机器(SN = 序列号)及其每个来源的资金,所以我想使用行跨度。每行都将是组件的实例,因为有自己的复选框,我想稍后使用它。问题是我不知道如何使用循环来创建表内有点复杂的组件。这是示例:
<div id="container">
<table border="1">
<template v-for="row in storage.rows">
<tr>
<td rowspan="2"><input type="checkbox"></td>
<td rowspan="2">{{row.sn}}</td>
<td>{{row.source}}</td>
</tr>
<tr>
<td>{{row.pair.source}}</td>
</tr>
</template>
</table>
</div>
<script>
new Vue({
el: '#container',
data: {
storage: {
rows: [
{sn: 111, source: 'EK', pair: {source: 'VLT', in: 100}},
{sn: 222, source: 'EK', pair: {source: 'VLT', in: 200}}
]
}
},
});
</script>
这工作正常,但我不知道如何将模板转换为组件。对于 Vue.js,我使用 Laravel 及其模板引擎 Blade,所以我有这样的解决方法:
<div id="container">
<table border="1">
@foreach($differences as $difference)
<tr is="ek" diff="{{ json_encode($difference) }}"></tr>
<tr is="vlt" diff="{{ json_encode($difference->pair) }}"></tr>
@endforeach
</table>
</div>
<template id="ek-template">
<tr>
<td rowspan="2"><input type="checkbox"></td>
<td rowspan="2">@{{ difference.sn }}</td>
<td>@{{ difference.source }}</td>
</tr>
</template>
<template id="source-template">
<tr>
<td>@{{ difference.source }}</td>
</tr>
</template>
<script>
new Vue({
el: '#container',
data: {
storage: {
differences: {!! json_encode($differences) !!}
}
},
components: {
ek: {
template: '#ek-template',
props: ['diff'],
computed: {
difference: function () {
return JSON.parse(this.diff);
},
},
},
vlt: {
template: '#source-template',
props: ['diff'],
computed: {
difference: function () {
return JSON.parse(this.diff);
},
},
}
},
});
</script>
我想使用 Vue.js 循环代替 Laravel 的 foreach
因为我已经在 Vue.js 对象中保存了数据。有什么解决办法吗?
最佳答案
您不需要混合使用blade和vue js模板。
你的例子是正确的,你只需要转换成单文件组件的VueJs组件即可。 (文件 *.vue)vue 组件结构是
// template should only have one root (e.g. wrap in div)
<template>
<div id="container">
<table border="1">
<template v-for="row in storage.rows">
<tr>
<td rowspan="2"><input type="checkbox"></td>
<td rowspan="2">{{row.sn}}</td>
<td>{{row.source}}</td>
</tr>
<tr>
<td>{{row.pair.source}}</td>
</tr>
</template>
</table>
</div>
</template>
<script>
export default {
// a data has to be a function within a vue component
data () {
return {
storage: {
rows: [
{sn: 111, source: 'EK', pair: {source: 'VLT', in: 100}},
{sn: 222, source: 'EK', pair: {source: 'VLT', in: 200}}
]
}
}
}
}
</script>
// styling for a template
<style>
</style>
一个新的 laravel 5.3 项目预装了一个示例 vue 组件。您可以使用它作为引用,并使用 gulp 将所有 vue 组件(*.vue)编译到单个文件(例如 app.js)
关于javascript - Vue.js - 具有两个行跨度的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40758707/