找不到上下文...
Vue.component("custom-table", {
name: 'CustomTable',
template: "#custom-table",
created: function() {
console.log('Created', this.rows);
},
mounted: function() {
console.log('Mounted', this.rows);
},
data: function() {
},
props: {
rows: Array
}
});
<script type="text/x-template" id="custom-table">
<table>
<thead>
<slot name="head"></slot>
</thead>
<tbody slot name="body">
</tbody>
</table
</script>
<custom-table :rows="myRows">
<thead slot="head">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody v-for="it in myRows">
<tr slot="body">
<td>{{ it.name }}</td>
<td>{{ it.ange }}</td>
</tr>
</tbody>
</custom-table>
我收到此错误..
Property or method "it" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. (found in root instance)
并且 myRows
是
[
{ name: 'Name1', age: 20 },
{ name: 'Name2', age: 30 }
]
最佳答案
您只是不能在表之外使用 thead 和 tbody 元素 - 在解析过程中浏览器会将代码“修复”为您的代码:) 顺便说一句,这是众所周知的、记录在案的警告。所以,改进你的代码。我以这种方式使用自定义表格:
Vue.component("custom-table", {
name: 'CustomTable',
template: "#custom-table",
props: {
cols: Array,
rows: Array
}
})
new Vue({
el: '#app',
data: {
myRows: [
{name: 'Name1', age: 20},
{name: 'Name2', age: 30}
]
}
})
<div id="app">
<custom-table
:cols="['Name', 'Age']"
:rows="myRows"
></custom-table>
</div>
<script type="text/x-template" id="custom-table">
<table>
<thead>
<tr>
<th v-for="col in cols">{{ col }}</th>
</tr>
</thead>
<tbody>
<tr v-for="it in rows">
<td>{{ it.name }}</td>
<td>{{ it.age }}</td>
</tr>
</tbody>
</table>
</script>
<script src="https://unpkg.com/vue"></script>
关于javascript - 插槽上下文未获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47654442/