无渲染组件中的Vue绑定引用

时间:2018-09-23 16:48:42

标签: javascript vue.js vuejs2 vue-component

我有一个问题,在无渲染组件中绑定ref无效。我尝试在classinstance object绑定工作中添加class,但ref没有。我还尝试记录this.$refs,但它只返回一个空对象。

App.vue

<template>
  <div id="app">
    <renderless>
      <div slot-scope="{ instance, logger }">
        <div v-bind="instance"></div>

        <button @click="logger('One')">One</button>
        <button @click="logger('Two')">Two</button>
      </div>
    </renderless>
  </div>
</template>

<script>
import Renderless from "./components/Renderless";

export default {
  components: {
    Renderless
  },
};
</script>

组件/Renderless.vue

<script>
export default {
  render(h) {
    return this.$scopedSlots.default({
      instance: {
        ref: 'container'
      },
    })
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      console.log(this.$refs)
    },
    logger(value) {
      console.log(value)
    },
  },
};
</script>

如何绑定ref,以便子组件知道要定位的元素或其他更好的解决方案/建议?

BTW代码在codesandbox上也可用。

1 个答案:

答案 0 :(得分:0)

您可以使用querySelectorquerySelectorAll在子组件中选择所需的内容。安装组件后,this.$el应该提供子类的基础元素。

init () {
  const buttons = this.$el.querySelectorAll('button');
  buttons.forEach(button => {
    // access each button
  });

  // fetches an item by element id
  const itemById = this.$el.querySelector('#elementid');

  // fetches by classes
  const itemsByClass = this.$el.querySelector('.className');
}
相关问题