【问题标题】:How to use JSON data in Scoped area of VUE Component如何在 VUE 组件的 Scoped 区域中使用 JSON 数据
【发布时间】:2020-07-13 03:41:28
【问题描述】:

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

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

我在 Vue 组件中使用 v-html 得到了 HTML 值。

但现在我想从我的 VUE 组件的 CSS Scoped 区域中的 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>

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component vuex


    【解决方案1】:

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

    但是,如果您想将样式应用于 &lt;div&gt; 元素,您当前的代码应该可以工作,只需将样式包含在大括号内即可:

    {
       "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/

    【讨论】:

    • 我已经尝试过了,但是 css 应该在
    猜你喜欢
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 2020-07-14
    • 2017-12-01
    • 2021-12-08
    • 2017-12-25
    • 2020-02-22
    相关资源
    最近更新 更多