在Vue中获取插槽数据作为变量? [英] Get slot data as a variable in Vue?

查看:15
本文介绍了在Vue中获取插槽数据作为变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件 (prism-editor),它只从 v-model="code" 获取代码.这意味着,代码必须通过 code:

I have a component (prism-editor) that only takes code from v-model="code". This means, the code has to be sent to the component through code:

<template>
  <prism-editor class="my-editor" v-model="code" 
    :highlight="highlighter" :line-numbers="numbers"/>
</template>

<script>  
  import { PrismEditor } from 'vue-prism-editor';

  export default {
    components: {
      PrismEditor,
    },
    data: () => ({
        code: this.$slots,
        numbers: true
    }),
  }
</script>

我想从一个插槽中名为 Code 的父组件绑定它:

I would like to bind this from a parent component named Code from a slot:

<template>
    <code language="c">
        int main() {
            printf('Hello World!');
        }
    </code>
<template>

<script>
  import Code from 'code.vue'
  export default {
    components: {
      'code': Code
    }
  }
</script>

在我的 Code 组件中,我必须找到一种方法来获取插槽数据并将其直接传递给 code 变量以发送到 v-模型='代码'.不幸的是,以下不起作用,因为我不知道如何从父 slot 获取数据:

In my Code component, I have to find a way to get and pass the slot data directly to the code variable to be sent to the v-model='code'. Unfortunately the following doesn't work because I don't know how to get the data from the parent slot:

data: () => ({
    code: this.$slots // Which obviously doesn't work...
})

换种说法,我只想获取在 code 标签内发送的所有原始内容:

Said differently, I just want to get all the raw content that was sent inside the code tag:

<code>all this content...</code>`

这可能吗?

推荐答案

好问题,为了解决这个问题,你必须在 Vuejs 下一层,并使用来自 DOM 的属性 textContentAPI [在这里阅读更多]

解决方案

使用此属性,您可以访问 DOM 元素内部的内容,因此在您的情况下,它将类似于:

Great question, in order to solve that you would have to go a layer below Vuejs, and use the property textContent from the DOM API [read more here]

With this property you can access the content inside of a DOM element, so in your case it would be something like:

/** Javascript*/this.$refs.mySlot.textContent;

/* * Template */ <div ref="mySlot"> <slot></slot> </div> /* * Javascript */ this.$refs.mySlot.textContent;

我在 Codesandbox 中为您设置了一个很好的示例:

I've setup a nice example for you in Codesandbox:

https://codesandbox.io/s/gallant-resonance-7unn2?file=/src/components/Code.vue

对于未来的挑战:

总是尝试看看是否可以用纯 Javascript 解决它.快乐的编码伙伴;

Always try to see if you can solve it with pure Javascript. Happy coding mate;

这篇关于在Vue中获取插槽数据作为变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆