簡體   English   中英

如何為 Vue.js 組件創建自定義樣式屬性

[英]How to create a custom style property for a Vue.js component

我正在嘗試使用 Vue.js 而無需構建步驟。 但是 Vue 沒有 style 屬性。

所以我有一個想法,在我的 Vue 組件實例上創建一個自定義的“樣式”屬性,然后在創建或安裝組件時將這個屬性的內容注入到 DOM 中。

唯一的問題是我不明白該怎么做。 (我查看了插件文檔)。 我需要創建某種插件,該插件首先檢查“樣式”屬性是否存在,然后將其插入到 DOM 中。 另外我不想使用 Vue.component() 函數,因為我想使用 ES6 導入和導出。 結果如下所示:

// MyComponent.js
export default {
  template: `<div>My component</div>`,

  style: `
    .hello {
      background: #ccc;
    }
  `,
}

// App.js
import MyComponent from './MyComponent.js'

new Vue({
  el: '#app',

  components: {
    MyComponent
  }
})

創建 MyComponent 時,它應該采用“style”屬性的值並將其添加到 DOM 中,如下所示。 任何想法將不勝感激。

$('body').append('<style>' + STYLE + '</style>')

這是一個使用 Vue.component() 函數的插件。 但我不想使用組件功能。

https://github.com/NxtChg/pieces/tree/master/js/vue/vue-css

您可以使用v-bind:style或簡稱:style來使用計算的內聯樣式。 它會將給定的對象映射到正確的 CSS 樣式。 使用駝峰命名,即backgroundColor而不是background-color

如果您想要全局樣式,您可以使用已mounted生命周期鈎子將樣式標簽注入到 head 中。 您應該在destroyed再次刪除它。

編輯:我誤解了你的帖子,更新了答案

 var app = new Vue({ el: '#app', data: { subject: 'World' }, computed: { subjectStyle() { return { color: 'yellow', backgroundColor: 'rebeccapurple', }; } }, mounted() { const css = ` body { background-color: #eee; font-family: 'Comic Sans MS', sans-serif; } `; this.styleTag = document.createElement('style'); this.styleTag.appendChild(document.createTextNode(css)); document.head.appendChild(this.styleTag); }, destroyed() { this.styleTag.remove(); } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> Hello, <span :style="subjectStyle">{{ subject }}</span>! </div>

下面是一個插件的一些代碼,它允許每個 Vue 實例指定一些樣式。 樣式將被注入<head>並在組件銷毀時再次刪除。

 const StylePlugin = { install(Vue) { Vue.mixin({ mounted() { const css = this.$options.style; if (!css) return; this.$styleTag = document.createElement('style'); this.$styleTag.appendChild(document.createTextNode(css)); document.head.appendChild(this.$styleTag); }, destroyed() { if (this.$styleTag) { this.$styleTag.remove(); } } }); } }; Vue.use(StylePlugin); var app = new Vue({ el: '#app', data: { subject: 'World' }, style: ` body { background-color: rebeccapurple; color: white; font-family: 'Comic Sans MS', sans-serif; } `, })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> Hello, World </div>

暫無
暫無

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

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