[英]Pass data variable as argument in style section of vue2
讓我們有一個數據變量,我想將這個數據變量用於我的風格。
data()
{
return{
selected:{
index: 2
}
}
}
<style>
.parent-table >>> .table-row:nth-child(/* here i want to pass selected.index */) {
background: red;
}
</style>
我的用例是我的登錄頁面中使用了一個表格組件。 我想從我的登錄頁面更改所選表格行的背景。
這就是將數據屬性傳遞給 css 屬性的方式。
<script>
export default {
data: () => ({
color: 'red',
}),
};
</script>
<style scoped>
.card-text-color {
color: v-bind(color)
}
如果您有一個自定義表格,那么根據我的理解,最好的方法是更新表格的行定義/配置中的顏色,而不是在<styles>
中進行硬編碼。
另外,我認為我們沒有根據您在Vue 2
中的要求提供任何解決方案。 在Vue 3.2
中,他們引入了這個特性,可以在<style>
標簽中啟用組件狀態驅動的動態 CSS 值。 你可以here
讀出來。
所以我的建議是為每組行分配一個顏色屬性,然后單擊該行為該屬性分配一些顏色代碼,然后使用動態 class 綁定,將其添加到模板中。 這是我想說的演示。
new Vue({ el: '#app', data: { items: [{ id: 1, name: 'Alpha', color: 'lightgray' }, { id: 2, name: 'Beta', color: 'lightgray' }, { id: 3, name: 'Gamma', color: 'lightgray' }, { id: 4, name: 'Omega', color: 'lightgray' }] }, methods: { getSelected(id) { this.items.forEach(obj => { if (obj.id === id) { obj['color'] = 'yellow' } }); } } })
table, thead, th, td { border: 1px solid black; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <table> <thead> <tr> <th>ID</th> <th>Name</th> </tr> </thead> <tbody> <tr v-for="item in items":key="item.id" @click="getSelected(item.id)":style="`background-color: ${item.color}`"> <td>{{ item.id }}</td> <td>{{ item.name }}</td> </tr> </tbody> </table> </div>
我不知道該怎么解釋。 但這里是如何將variables
傳遞給style scope
PROPS
:
props: {
bgColor: {
type: String,
default: "#ff0000" //RED
}
},
COMPUTED
(可用作參數的變量):
computed: {
tableRowColor() {
return {
'--bg-color': this.bgColor,
'--index': this.selected.index //from your data
}
}
}
訪問style scoped
內的variables
的示例:
<style scoped>
table, td, th {
border: 1px solid;
}
table {
width: 100%;
background: var(--bg-color); /*here is how to access the variable */
}
</style>
注意:如果您只想從data
中獲取index
,則不需要制作道具
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.