Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

关于slot插槽的v-slot指令用法--作用域插槽

问题描述

按照文档使用v-slot指令,获取作用域插槽的值
报错:Property or method "slotProps" is not defined on the instance but referenced during render.

问题出现的环境背景及自己尝试过哪些方法

按照文档使用v-slot指令,获取作用域插槽的值

相关代码

文档的写法

<current-user>
  <template v-slot:default="slotProps">
    {{ slotProps.user.firstName }}
  </template>
</current-user>

我的写法

<!-- 基础组件-InputItem -->
  <!-- 其他内容。。。 -->
  <slot name="label"><div class="label">{{label}}</div></slot>
  <!-- 其他内容。。。 -->
<!--  -->


<!-- 父组件-InputList -->
<InputItem v-for="count in 10" :key="count">
  <!-- 其他内容。。。 -->
  <template v-slot:label>
       <slot name="label" v-bind="props"></slot>
  </template>
  <!-- 其他内容。。。 -->
</InputItem>
<!--  -->

<!-- 使用了作用域插槽的地方 -->
<InputList>
  <!-- 其他内容。。。 -->
  <template v-slot:label="slotPropt">
       {{slotPropt}}
  </template>
  <!-- 其他内容。。。 -->
</InputList>
<!--  -->

你期待的结果是什么?实际看到的错误信息又是什么?

期待的结果:正常渲染

实际错误信息:

浏览器控制台输出
[Vue warn]: Property or method "slotProps" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

实际上我认为这个报错实际上是对的,按照指令的语法,slotProps确实是未定义的,因为指令的传参,意义是vue组件实例里面的变量。
这是否是文档的写法或者slot插槽的实现存在某些语法的歧义?
我现在想要知道的是,在这种情况下我该怎么处理?

看到别的同学都能正常使用,我想也许是我用错了,但是我也不知道错误的地方在哪,希望知道的同学能够帮我指正,谢谢


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

报错是因为,你自己的组件内的 data、computed 或者 props 没有初始化 slotProps,你的用法有问题

正确写法是:

<!-- 父组件-InputList -->
<InputItem v-for="count in 10" :key="count">
  <template v-slot:label :count=count>
        // 把 props 作为 slot 元素的一个属性
       <slot name="label" v-bind:props="props"></slot>
  </template>
</InputItem>


<!-- 使用了作用域插槽的地方 -->
<InputList>
  <template v-slot:label="{ props }">
    <!-- 插槽内容 -->
    {{props}}
  </template>
</InputList>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...