vue组件this。$ children始终为空

时间:2019-01-20 14:19:06

标签: javascript html vue.js

这是我的代码:

<head>
  <meta charset="utf-8">
  <!--mobile friendly-->
  <meta name="viewport" content="width=device-width, user-scalable=yes">
  <script type="text/javascript" src="../../node_modules/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
  <selection>
    <selection-item></selection-item>
    <selection-item></selection-item>
  </selection>
</div>
<script>
  Vue.component("selection", {
    mounted: function () {
      var c = this.$children
      console.log(c)
    },
    template: `<div></div>`
  })
  new Vue({el: "#app"})
</script>
</body>

输出为Array(0),但是在我的代码中,选择具有子选择项,因此如何获取vue组件“选择”的子项“选择项”

这是我的vue版本:

roroco@roroco ~/Dropbox/js/ro-js/node_modules/vue $ cat package.json |gr version
  "_nodeVersion": "8.4.0",
  "_npmVersion": "5.4.1",
  "version": "2.4.4"

2 个答案:

答案 0 :(得分:0)

基于$children上的文档:

  

当前实例的直接子组件。 请注意,$children没有订单保证,并且没有反应。如果您发现自己尝试使用$children进行数据绑定,请考虑使用Array和v-for生成子组件,并将Array用作真相的来源。

另一种选择是利用$slots来保存包裹在VNode interface中的直接子组件。

Vue.component("selection", {
  mounted() {
    var children = this.$slots.default;
    
    //console.log(children);
  },
  template: `
    <div>
      <slot></slot>
    </div>`
});

Vue.component("selection-item", {
  template: `<div></div>`
});

new Vue({
  el: "#app"
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <selection>
    <selection-item></selection-item>
    <selection-item></selection-item>
  </selection>
</div>

如果您需要这些子元素作为HTML元素,它们将位于同一包装器内的elm属性下。另请注意,尽管名称为单数,this.$slots.default实际上是一个数组。像这样

const children = this.$slots.default
  .map(vnode => vnode.elm)
  .filter(el => el.tagName === 'DIV');

答案 1 :(得分:0)

我找到了解决方案:我应该在vue组件模板中添加<slot></slot>,这是工作代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <!--mobile friendly-->
  <meta name="viewport" content="width=device-width, user-scalable=yes">
  <script type="text/javascript" src="../../node_modules/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
  <selection>
    <selection-item></selection-item>
    <selection-item></selection-item>
  </selection>
</div>
<script>
  Vue.component("selection-item", {
    template: `<div>prpr</div>
  `
  })
  Vue.component("selection", {
    mounted: function () {
      var c = this.$children
      console.log(c)
    },
    template: `<div><slot></slot></div>`
  })
  new Vue({el: "#app"})
</script>
</body>
</html>