javascript - 如何在VUE组件的Scoped区域中使用JSON数据

标签 javascript vue.js vuejs2 vue-component vuex

我想在 VUE 组件的 Scoped 区域中使用我的 JSON 数据。

所以基本上我的 Json 文件包含 CSS 样式作为文本和 HTML 标签。

我在Vue组件中使用v-html获取了HTML值。

但现在我想从 VUE 组件的 CSS 范围区域中的 JSON 文件访问 CSS 值。

我的 JSON

{
    "elements":[
           {
             "id":"11",
             "html":"<button>this is button</button>",
             "css":"button{color:#f00;}",
             "author":"Test"
           }
    ]
}

======================

我的 VUE 组件

<template>
<div class="collection">
    <section class="section section-elements">
        <div class="container container--large">
            <div class="row">
                <div class="col-sm-3" v-for="(item, index) in json.elements" v-bind:key="index">
                    <div class="elements">

                        <div class="elements-head" v-html="item.html" :style="item.css">

                        </div>
                        <div class="elements-main">
                            <p>{{ item.css }}</p>
                        </div>
                        <div class="elements-foot">
                            <p>{{ item.author }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

最佳答案

不可能动态创建范围内的 css 样式,因为这些样式是由 vue-router 在构建期间而不是在客户端中创建的。

但是,如果您想将样式应用到<div>,您当前的代码应该可以工作。元素,只需将样式包含在大括号内:

{
   "id":"11",
   "html":"<button>this is button</button>",
   "style":"font-size:18vw;color:#f00;",
   "author":"Test"
}

<div class="elements-head" v-html="item.html" :style="item.style">

示例:https://jsfiddle.net/ellisdod/q3L5ahke/

动态组件

但是,如果您想将样式应用于元素,最好使用动态组件。这样做的缺点是您需要将所有 html 脚本注册为组件 - 您可以编写一个循环来通过 json 以编程方式执行此操作。

Vue.component('MyButton',{
template:'<button>this is button</button>'
})
{
    "id":"11",
    "component":"MyButton",
    "style":"font-size:18vw;color:#f00;",
    "author":"Test"
}
<component :is="item.component" :style="item.style">

示例:https://jsfiddle.net/ellisdod/oju1m7q8/

关于javascript - 如何在VUE组件的Scoped区域中使用JSON数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60970055/

相关文章:

javascript - 如何替换句子中多个位置的文本?

javascript - ng-class - 错误 : Token '-' is at column {2}

html - 如何制作表格行中某些(但不是全部)表格单元格的 Vue.js 组件?

vue.js - 我可以在同一个应用程序中拥有多个 SPA 或在同一个应用程序中使用历史记录和哈希路由吗?

javascript - 是否可以将函数传递给 Ember.js 组件以将其作为 Action 回调执行?

javascript - 如何使用POST方法感知和访问参数

javascript - 尝试使用 vue 和 webpack : __WEBPACK_IMPORTED_MODULE_3_keycloak_js__ is not a function 安装 keycloak-js 时出现未捕获的类型错误

javascript - 如何在 VueJs 中将值从函数传递到变量?

javascript - 自定义指令进行组件渲染

vue.js - 删除子组件(行)的意外行为