简体   繁体   English

Vue.component() 中的计算属性

[英]computed property within a Vue.component()

I am learning Vue.js 2. I want to create a custom component like this: <bs-container fluid="true"></bs-container> and I would like Vue.component() to take care of the bootstrap 3 container classes behind the scenes based on the boolean value passed in the fluid prop, because <bs-container fluid="true"></bs-container> looks much cleaner than div class="container-fluid></div> . This is my attempt so far, but it's not working:我正在学习 Vue.js 2。我想创建一个这样的自定义组件: <bs-container fluid="true"></bs-container>并且我希望 Vue.component() 负责引导程序 3基于fluid属性中传递的布尔值在幕后的容器类,因为<bs-container fluid="true"></bs-container>看起来比div class="container-fluid></div>干净得多。到目前为止,这是我的尝试,但它不起作用:

HTML: HTML:

<div id="app" >
<bs-container fluid="false">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</bs-container>

JS: JS:

Vue.component('bs-container',{
props: ['fluid'],
template: '<div class="setClass"><slot></slot></div>',
computed: {
    setClass: function() {
        console.log('setClass has been called');
        if (this.fluid == true) {
            return 'container-fluid';
        } else{
            return 'container';
        }
    }
}
}); 
new Vue({
        el: '#app'
});

The setClass method is not being invoked.未调用 setClass 方法。 What am I missing?我错过了什么?

You have to bind the class if you want to make it dynamic with computed property as you can see here https://v2.vuejs.org/v2/guide/class-and-style.html .如果要使用计算属性使其动态化,则必须绑定该类,如您在此处看到的https://v2.vuejs.org/v2/guide/class-and-style.html Also I would check if the string passed is equal just avoid some nasty truthy falsy conversion.另外我会检查传递的字符串是否相等,只是避免一些讨厌的真假转换。

Vue.component('bs-container',{
props: ['fluid'],
template: '<div :class="setClass"><slot></slot></div>',
computed: {
    setClass: function() {
        console.log('setClass has been called');
        if (this.fluid === 'true') {
            return 'container-fluid';
        } else{
            return 'container';
        }
    }
}
}); 
new Vue({
        el: '#app'
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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