如何将对象传递给web组件生成的宽度Vue?



组件必须呈现一个对象来填充内容。当我在Vue项目中工作时,用

传递这个对象没有问题。
<my-compnent :card="card"></my-component>

但是当我尝试使用构建的组件时,它不读取"MyCard"作为一个对象,它读起来像一个字符串…请帮帮我

我已经尝试了同样的方法,使用:card,但它不起作用,如果我只使用card="card"它可以访问组件,但没有对象

我代码:

<script>
card =
{
name: 'card',
graphic: 'https://static.anychart.com/images/gallery/v8/line-charts-line-chart.png',
subtitle: 'about this card',
info: 'this is a test content card',
selector1: [
{ name: 'opt 1' },
{ name: 'opt 2' },
{ name: 'opt 3' }
],
selector2: [
{ name: 'opt A' },
{ name: 'opt B' },
{ name: 'opt C' }
]
}
</script>
<script src="https://unpkg.com/vue"></script>
<body>
<my-component card="card"></card>
</body>

和错误:

[Vue warn]:无效的道具:道具"卡片"类型检查失败。

期望对象,得到值为&;card&;的字符串。我也试过

<my-component :card="card"></card>

,但这只适用于vue项目,而不适用于导出的web组件。它给出如下错误:

[Vue warn]:渲染错误:"TypeError:不能访问属性"name", _vm。卡片未定义">

card="card"将字符串'card'作为值传递给card属性。如果你想把JS对象传递给Vue外部的一个导出的web组件,那么你必须在JS中自己做。

<script>
const card =
{
name: 'card',
graphic: 'https://static.anychart.com/images/gallery/v8/line-charts-line-chart.png',
subtitle: 'about this card',
info: 'this is a test content card',
selector1: [
{ name: 'opt 1' },
{ name: 'opt 2' },
{ name: 'opt 3' }
],
selector2: [
{ name: 'opt A' },
{ name: 'opt B' },
{ name: 'opt C' }
]
}
let comp = document.querySelector('my-component')
comp.card = card
</script>
<body>
<my-component card="card"></card>
</body>

你可以使用v-bind:card或简单的':card'只有当你在vue项目中工作,在这种情况下,你不需要使用导出的组件。但是在这种情况下,对象card需要传递给Vue实例的data属性,否则Vue无法找到它。这就是你得到错误的原因。

<script>
const app = new Vue({
el: '#app',
data: {
card,
},
}
</script>
<my-element :user.prop="{ name: 'jack' }"></my-element>
<!-- shorthand equivalent -->
<my-element .user="{ name: 'jack' }"></my-element>

最新更新