繁体   English   中英

传递将在子组件样式中使用的道具 - Vue

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM