在Vue中的组件脚本中使用插槽范围的数据

时间:2018-05-18 11:21:51

标签: javascript vue.js

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

组件模板:

<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。我可以创建一个子组件(C),它接受myObject作为prop并拥有所有那里需要的逻辑,但我想避免这种情况。

1 个答案:

答案 0 :(得分:0)

如果你使用插槽范围,你基本上是从托管插槽的组件(而不是插槽的内容)将数据传递到插槽。 在您的情况下,如果要使用数据槽范围,则必须从组件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-scope="{myObject}"