[英]Passing props that will be used in style in child component - Vue
我有一個運行 function startProcess
的按鈕,它將生成一個隨機數。 這個隨機數將作為一個 prop 傳遞給Child.vue
以用於樣式。 我查看了一些頁面How to use props in style in vue 。 解決方案是使用computed
,但似乎沒有任何效果。 為了更好地理解,請檢查代碼。
PS這是一個簡化的代碼。 刪除了template, script, style
。
應用程序.vue
<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);
};
試試下面的代碼片段:
Vue.component('Child', { template: ` <div class=""> <button @click="logTop" class="foo":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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.