VueJS 错误避免直接改变道具

新手上路,请多包涵

我正在尝试创建一个模式,但只有在关闭它时才会出现此错误:

 [Vue warn]: 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"

found in

---> <PanelDesconectarModal> at resources\assets\vue\PanelDesconectarModal.vue
       <VNavigationDrawer>
         <PanelDrawer> at resources\assets\vue\PanelDrawer.vue
           <VApp>
             <PanelRoot> at resources\assets\vue\PanelRoot.vue
               <VApp>
                 <Root>

PanelDesconectarModal.vue

 <template>
    <v-dialog v-model="value" max-width="350">
        <v-card :dark="($theme === 'dark')">
            <v-card-title class="headline">Desconectar</v-card-title>
            <v-divider></v-divider>
            <v-card-text>Você tem certeza que deseja desconectar-se?</v-card-text>
            <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn flat @click.native="closeDialog">Cancelar</v-btn>
                <v-btn :color="$color" flat="flat" @click.native="desconectar">Desconectar</v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
</template>

<script>
    export default {
        name: 'panel-desconectar-modal',
        props: ['value'],
        methods: {
            closeDialog() {
                this.value = false;
            },
            desconectar() {
                this.closeDialog();

                window.location = this.$route + '/panel/desconectar';
            }
        }
    }
</script>

使用ProgressDesconectarModal.vue,showDesconectar是数据变量

<panel-desconectar-modal :value="showDesconectar"></panel-desconectar-modal>

原文由 Rafael de Azeredo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 431
2 个回答

发生这种情况是因为您的 value v-model

Do not do that, as that will mutate the prop( value ) when v-model changes (you should only change data values with v-model afaik,但在这种情况下,您甚至不需要额外 data 变量)。

从vuejs v2.3.0开始,建议将 emit 的值传给父 组件,让父组件改变,再传给子组件。


所以你所要做的就是:

v-dialog 组件

删除 v-model 并将其替换为 :value="value" @input="$emit('input')"

你的功能:

 closeDialog() {
    this.$emit('input');
}

panel-desconectar-modal 组件使用 v-model="showDesconectar"


这将起作用 ,因为

>  <input v-model="something"> is syntactic sugar for:
>
> <input
>
> ```

 v-bind:value="something"
v-on:input="something = $event.target.value">

”`

这是我在 回答 类似问题 时提供的 工作示例笔

原文由 Traxo 发布,翻译遵循 CC BY-SA 4.0 许可协议

你不应该改变你的子组件中的道具。您只能改变对象而不能改变基元。因此,您可以使用数据选项或计算属性:

 data() {
  return {
    childValue: this.value; // initialize props value
  }
}

现在,您可以更改 childValue

 closeDialog() {
   this.childValue = false;
},

确保在子组件中的所有位置都使用 childValue 而不是 value 道具。

原文由 Bhojendra Rauniyar 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题