传递将在子组件中用于样式的道具 - Vue
Passing props that will be used in style in child component - Vue
我有一个运行函数 startProcess
的按钮,它会生成一个随机数。这个随机数将作为道具传递给将在样式中使用的 Child.vue
。
我查看了一些页面 How to use props in style in vue。解决方案是使用 computed
,但似乎没有任何效果。为了更好的理解,请查看代码。
P.S。这是一个简化的代码。删除了 template, script, style
.
App.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();
};
}
Child.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>
我有一个运行函数 startProcess
的按钮,它会生成一个随机数。这个随机数将作为道具传递给将在样式中使用的 Child.vue
。
我查看了一些页面 How to use props in style in vue。解决方案是使用 computed
,但似乎没有任何效果。为了更好的理解,请查看代码。
P.S。这是一个简化的代码。删除了 template, script, style
.
App.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();
};
}
Child.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>