Vue中使用插槽/具名插槽传值,父组件引用报错:Converting …… JSON at JSON.stringify?

1.实例

// 子组件
<slot :name="item.prop" :scope="scope">

// 父组件
<template slot="xxx" slot-scope="scope">
{{scope}}
</template>

页面报错:
Converting circular structure to JSON at JSON.stringify

但是,只要在父组件中直接使用{{scope.arrName}} 就能正常。

2.原因

{{}} 就是使用了JSON.stringify格式化数据,而 JSON.stringify 是不能用于有循环引用的对象,比如:

const data = {};
data.myself = data;
JSON.stringify(circularReference);
// 报错: "Uncaught TypeError: Converting circular structure to JSON"
// 含义:未捕获类型错误:将循环结构转换为JSON

vue 中的 scope 一般都包含有循环引用,所以会报错;只能需要哪个值就直接取哪个值(比如 {{scope.arrName}} ),如果想查看 scope 里到底有那些属性,一般可以这样:

<template slot="xxx" slot-scope="scope">
  <button @click="action(scope)">打印 scope 值</button>
</template>
<script>
exprot default {
  methods: {
      action(val) {
        console.log(val);
      },
  }
}
</script>
posted @ 2022-12-06 22:17  轻风细雨_林木木  阅读(77)  评论(0编辑  收藏  举报