【问题标题】:Use slot-scoped data in the component script in Vue在 Vue 的组件脚本中使用 slot-scoped 数据
【发布时间】:2018-10-28 19:55:15
【问题描述】:

在 vue 中,我有一个带有插槽的组件 A,它使用它返回一个对象作为组件 B 中的插槽范围:

组件A模板:

<template>
<div>
   <slot :myObject="myObject" />
</div>
</template>

B 组件模板:

<template>
<component-a>
  <template slot-scope="{myObject}">
    <!-- uses myObject -->
  </template>
</component-a>
</template>

<script>
  module.exports={
     data(){
       return {
          myObject: null // This never updates with the new value
       }
     }
  }
 </script>

在组件 B 的 html 模板中一切正常,但是,我无法在组件 B 的脚本中访问 myObject。我可以创建一个接受 myObject 作为道具并拥有所有需要的子组件 (C)那里有逻辑,但我想避免这种情况。

【问题讨论】:

  • 这似乎不适合使用插槽范围。一个简单的道具就足够了。

标签: javascript vue.js


【解决方案1】:

如果您使用 slot-scope,您基本上是将数据从托管插槽的组件传递到插槽(而不是插槽的内容)。 在您的情况下,如果要使用数据槽范围,则必须从组件 A 传递数据。因此数据源 myObject 必须存在于组件 A 中。

所以正确的方法应该是这样的:

组件 A

<template>
    <div>
        <slot :myObject="myObject" />
        <button @click="changeMyObject">Change MyObject</button>
    </div>
</template>
<script>
    export default {
        name: "slot-scope-component",
        data(){
            return {
                myObject: {
                    value: "ABC"
                }
            }
        },
        methods:{
            changeMyObject() {
                this.myObject = {
                    value: "XYZ"
                };
            }
        }
    }
</script>

组件 B

<template>
    <ComponentA>
        <template slot-scope="props">
            {{props.myObject}}
        </template>
    </ComponentA>
</template>

<script>
    import ComponentA from '@/components/ComponentA';

    export default {
        components: {
            ComponentA
        },
    }
</script>

还有一点拼写错误:你写的是 slot-scoped 而不是 slot-scope

您可以使用解构进一步改进该代码:

slot-scope="{myObject}"

【讨论】:

  • 我不确定我是否理解你的例子,但是在组件A脚本中使用数据是没有问题的,我的问题是是否可以在组件B中使用它
  • 哦,这就是你的意思:你必须知道数据对象 myObject 只存在于 Slot 中而不存在于 componentB 本身中(它是从组件 A 传递到 slot 的,它的范围只是插槽,这就是为什么它被称为插槽范围)。如果你想在 componentB 中使用 myObject,那么你可以将它传递给这样的事件:@click="changeMyObject(myObject)"
猜你喜欢
  • 2020-07-13
  • 2020-10-24
  • 2017-10-15
  • 2021-10-30
  • 2021-10-31
  • 1970-01-01
  • 2020-09-24
  • 2022-01-22
  • 2017-12-01
相关资源
最近更新 更多