2017-09-08 97 views
0

我正在使用vue-switch切換開關,我需要知道它的狀態。根據https://www.npmjs.com/package/vue-switch的文檔,我只是應該使用:value.sync =「切換「開關組件中的一個名爲」切換「的數據屬性,我已經完成了。我收到以下錯誤:將Vue開關值綁定到數據道具

Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "value" vue switch found in ---> <Switcher> at E:\Dev\BackgroundCheck.Members\front-end\node_modules\vue-switch\switch.vue 

我的HTML:

<switcher size="lg" color="green" :value.sync="toggle"></switcher> 

我的JS:

<script> 
import mySwitch from 'vue-switch'; 

export default { 
    name: 'BackgroundReports', 
    components: { 
    'switcher': mySwitch 
    }, 
    computed: { 
    report() { return this.$store.getters.currentReport }, 
    isBeingMonitored() { return this.$store.getters.isBeingMonitored } 
    }, 
    mounted() { 
    this.toggle = this.isBeingMonitored; 
    } 
} 
</script> 

的switch.vue代碼:

<template> 
    <div :class="className" @click="onClick"> 
     <span class="open">{{ openName }}</span> 
     <span class="close">{{ closeName }}</span> 
    </div> 
</template> 

<script> 
'use strict'; 

export default { 
    props: { 
     value: { 
      default: true, 
      twoWay: true 
     }, 
     size: { 
      type: String, 
      default: 'md中' 
     }, 
     // blue red green orange 
     color: { 
      type: String, 
      default: 'red' 
     }, 
     openValue: { 
      default: true 
     }, 
     closeValue: { 
      default: false 
     }, 
     openName: { 
      type: String, 
      default: 'ON' 
     }, 
     closeName: { 
      type: String, 
      default: 'OFF' 
     }, 
     disabled: { 
      type: Boolean, 
      default: false 
     } 
    }, 
    computed: { 
     className() { 
      let { 
       value, 
       openValue, 
       closeValue, 
       size, 
       color, 
       disabled 
      } = this; 
      return { 
       'vue-switch': true, 
       'z-on': value === openValue, 
       'z-disabled': disabled, 
       ['s-' + size]: true, 
       ['c-' + color]: true 
      }; 
     } 
    }, 
    methods: { 
     onClick() { 
      let { 
       disabled, 
       value, 
       openValue, 
       closeValue 
      } = this; 
      if (!disabled) { 
       if (openValue === value) { 
        this.value = closeValue; 
       } else { 
        this.value = openValue; 
       } 
      } 
     } 
    } 
} 

</script> 
+0

我的猜測是vue-switch是爲Vue 1編寫的,其中這種事情是可以的。 –

+0

@RoyJ廢話......感謝輸入 – Linx

+0

爲了使它與Vue 2一起工作,你只需要用'$ emit'作爲'value'的行來替換賦給'value'的行。同步'現在工作](https://vuejs.org/v2/guide/components.html#sync-Modifier) –

回答

2

你」我們會注意到包中實際上有兩個組件。一個用於vue 1. *和一個用於vue 2。*。你只需要導入正確的。

import mySwitch from 'vue-switch/switch-2.vue'; 
+0

這工作!謝謝! – Linx