javascript - 插槽上下文未获取

标签 javascript vue.js vuejs2 vue-component

找不到上下文...

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/

相关文章:

javascript - Vue.js 动态组件 - 仅在组件内部获取数据时加载

spring-boot - 无法检索蓝图 'generator-jhipster-vuejs' 声明的 JHipster 版本

javascript - NuxtJS 中带有 Slug 参数的未知动态嵌套路由?

javascript - 通过编程导航 Vue.js 传递 Prop

javascript - 在 Notepad++ 中使用 jsDoc

javascript - 计算 JSON 中的值并将其转换为数字形式

javascript - JQuery - 仅当两个连续轮询不具有相同状态时才增加 div 标记中的计数器

javascript - 如何摆脱表行标题重复?

javascript - Vuejs : Show error messages as popups

javascript - 正则表达式仅引用字符串匹配(而不是数字)