簡體   English   中英

如何在VUE Component的Scoped區域使用JSON數據

[英]How to use JSON data in Scoped area of VUE Component

我想在 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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM