繁体   English   中英

Vue.js - 绑定到组件的道具没有显示正确的结果

[英]Vue.js - prop binded to component not showing the right result

我的 Vue.js 应用程序中有这个 SwitchButton 组件,它有一个自定义事件“切换”。 单击(切换)按钮时,切换事件将 isEnabled 设置为 false 或 true。 没有问题,但是当我将父组件中的 isEnabled 绑定到 SwitchButton 子组件以设置其初始值时,它似乎不起作用。

父组件中使用的代码(将 isEnabled 设为 true 作为初始值)

<SwitchButton v-model="distSwitch" :isEnabled="true">
    <label slot="left">{{ $t('general.dealer') }}</label>
    <label slot="right">{{ $t('general.wholesale') }}</label>
</SwitchButton>

开关按钮组件:

<template>
    <div class="switch-button-control">
        <div class="switch-button-label">
            <slot name="left"></slot>
        </div>
        <div class="switch-button" :class="{'enabled': isEnabled}" @click="toggle">
            <div class="button"></div>
        </div>
        <div class="switch-button-label">
            <slot name="right"></slot>
        </div>
    </div>
</template>

<script>
export default {
    name: 'SwitchButton',
    model: {
        prop: 'isEnabled',
        event: 'toggle'
    },
    props: {
        isEnabled: {
            type: Boolean,
            required: true
        }
    },
    methods: {
        toggle() {
            this.$emit("toggle", !this.isEnabled);
        }
    },
    created() {
        /*eslint-disable no-console*/
        console.log('isEnabled', this.isEnabled)
    }
}
</script>

我希望创建的钩子中的 console.log 输出“isEnabled > true”,但它输出“false”

我在这里缺少什么?

由于属性isEnabled的值是由硬编码的true设置的,因此从子组件更改它是行不通的。

在父组件中初始化一个数据变量并设置为属性可以在这里提供帮助。

模板:

<SwitchButton v-model="distSwitch" :isEnabled="isEnabled" @toggle="toggleIsEnabled">
    <label slot="left">{{ $t('general.dealer') }}</label>
    <label slot="right">{{ $t('general.wholesale') }}</label>
</SwitchButton>

数据:

data:()=>{
  return {
    isEnabled:true
  }
}

methods部分创建一个方法:

toggleIsEnabled:function(value){
   this.isEnabled = value;
}

使用自定义事件发射器toggleSwitchButton组件发出的值将触发父组件中的回调函数toggleIsEnabled

暂无
暂无

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

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