我有一個按鈕可以運行該函式startProcess,該函式將生成一個亂數。此亂數將作為道具傳遞給Child.vue將在樣式中使用的道具。我查看了一些頁面“如何在 vue 中使用樣式中的道具”。解決方案是使用computed,但似乎沒有任何效果。為了更好地理解,請檢查代碼。
PS 這是一個簡化的代碼。已洗掉template, script, style。
應用程式
<button @click="startProcess">Start</button>
<Child v-if="toggleChild" :top="top" />
data() {
return {
toggleChild: false,
top: 0
}
},
methods: {
startProcess() {
this.toggleChild = !this.toggleChild;
this.top = Math.random();
};
}
兒童.vue
<button @click="logTop">Log</button>
props: { top: Number },
computed: {
return {
cssProps() {
"--top": `${this.top}%`;
};
};
};
.foo {
top: var(--top);
};
uj5u.com熱心網友回復:
嘗試像以下片段:
Vue.component('Child', {
template: `
<div >
<button @click="logTop" :style="cssProps">Log</button>
</div>
`,
props: { top: Number, col: String },
methods: {
logTop() {
console.log(this.top)
}
},
computed: {
cssProps() {
return {
'--top': `${this.top}%`,
'--col': this.col
}
}
}
})
new Vue({
el: '#demo',
data() {
return {
toggleChild: false,
top: 0,
col: ''
}
},
methods: {
startProcess() {
this.toggleChild = !this.toggleChild;
this.top = Math.random()*100;
this.col = 'red'
}
}
})
Vue.config.productionTip = false
Vue.config.devtools = false
.foo {
position: absolute;
top: var(--top);
background-color: var(--col);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<button @click="startProcess">Start</button>
<Child v-if="toggleChild" :top="top" :col="col" />
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/372758.html
標籤:javascript Vue.js
