首页 > 解决方案 > 使用 EventBus 更新组件中的数据时出现问题

问题描述

我有一个 Switch-El 组件,我在其中根据值绘制一个矩形。

为什么这样的绑定在模板中不起作用,尽管值发生了变化。

Vue.component('switch-el', {
    props: [
        'props_id', 
        'props_name',
        'props_value',
    ],
    data: function() {
        return {
            id: this.props_id,
            name: this.props_name,
            value: this.props_value,

            fill: "#00c853",
            stateRotate: "m5.989 8.848h-4.5",
        };
    },
    computed: {
        turnSwith: function() {
            if (this.value === true) {
                this.fill = "#d50000";
                this.stateRotate = "m3.739 6.598v4.5";
            }
            else {
                return  this.filll = "#00c853";
                this.stateRotate = "m5.989 8.848h-4.5";
            }
        },
    },
    created(){
        console.log(eventBus);
        eventBus.$on("sendDeviceValue", data => {
            this.value = true;
        });
    },
    template: '#switch-el' // components/template.html
});
<script type="text/x-template" id="switch-el">
<g id="swbox">
    <g id="switch" transform="translate(11.23 66.794)" stroke="#102027" stroke-linecap="round" cursor="pointer">
        <rect id="switch_state_fill" x=".1894" y="5.2976" width="7.1" height="7.1" v-bind:fill="fill" stroke-width=".37867"/>
        <g fill="none" stroke-width=".4">
            <path id="switch_state_line" v-bind:d="stateRotate"/>
            <path id="path6" d="m3.739 0.2021v5"/>
            <path id="path6-8" d="m3.739 12.436v5"/>
        </g>
        <title>{{value}}</title>
    </g>
 </g>   
</script>

如果在模板中我替换

v-bind:fill="turnSwithFill"

并在计算添加

turnSwithFill: function() {
            if (this.value === true) {
                return "#d50000";
            }
            else {
                return  filll = "#00c853";
            }
        }

Everything works. But I like the first option more

标签: vue.jsevent-bus

解决方案


推荐阅读