简体   繁体   English

如何将 JSON 字符串作为道具传递?

[英]How can I pass a JSON string as a prop?

I am using Vue.js with Shopify, and I'm hoping to pass objects from Liquid into a Vue component as a prop.我正在使用 Vue.js 和 Shopify,我希望将 Liquid 中的对象作为道具传递到 Vue 组件中。 For example, if I register the Vue component product-tile, and I want to use Shopify's product object in Liquid and convert it directly into an object in Vue, I would like to be able to do something like this:例如,如果我注册了 Vue 组件 product-tile,我想在 Liquid 中使用 Shopify 的产品 object并在 Vue 中将其直接转换为 object,我希望能够执行如下操作:

<product-tile product='{{ product | json }}'></product-tile>

Note that the curly brackets here are Liquid and not Vue, I'm using delimiters .请注意,这里的花括号是 Liquid 而不是 Vue,我使用的是定界符 My current workaround is to put the data I need in hidden input fields that I then pull in from the DOM after the component is mounted, but being able to pass the Liquid directly into the Vue component would be a much cleaner solution.我目前的解决方法是将我需要的数据放在隐藏的输入字段中,然后在安装组件后从 DOM 中提取这些数据,但是能够将 Liquid 直接传递到 Vue 组件将是一个更简洁的解决方案。

I get errors with the above code because Vue doesn't seem to like a JSON string being passed in as a prop in this way.我在上面的代码中遇到错误,因为 Vue 似乎不喜欢以这种方式将 JSON 字符串作为 prop 传入。 The specific error is:具体报错是:

Template compilation error: Unquoted attribute value cannot contain U+0022 ("), U+0027 ('), U+003C (<), U+003D (=), and U+0060 (`).模板编译错误:未加引号的属性值不能包含 U+0022 (")、U+0027 (')、U+003C (<)、U+003D (=) 和 U+0060 (`)。

Is there a other way to accomplish this without my current workaround?如果没有我当前的解决方法,是否有其他方法可以实现此目的?

Looking at uicrooks/shopify-foundation-theme , they were able to make it work with an extra filter.查看uicrooks/shopify-foundation-theme ,他们能够使用额外的过滤器使其工作。

<product-tile :product="{{ product | json | replace: '"', "'" }}" />
<product-tile :product="product"></product-tile>

<product-tile :product="JSON.parse(product)"></product-tile>

and define prop as并将道具定义为

props: {
  product: Object
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM