如何用vuejs2自我关闭对话?

时间:2017-12-21 09:23:17

标签: vuejs2

我正在编写一个对话框组件,我不知道如何自己关闭对话框。

<template>
  <div class="dialog" v-show="visible">
    ...
    <button @click="close">Close</button>
  </div>
</template>
<script>
  {
    props: {visible: {type: Boolean, default: false}},
    methods: {
      close () {
        // this.visible = false //It will get vue warn
      }
    }
  }
</script>

那么,如何关闭组件中的对话框,我无法更新visible道具,我将收到错误。

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: "visible"

2 个答案:

答案 0 :(得分:2)

道具是one way data flow

您不应该改变从子组件中的父组件接收的道具

因此发出custom event来改变父组件本身的道具

<template>
  <div class="dialog" v-show="visible">
    ...
    <button @click="close">Close</button>
  </div>
</template>
<script>
  {
    props: {visible: {type: Boolean, default: false}},
    methods: {
      close () {
        // this.visible = false //It will get vue warn
        this.$emit('close-dialog')
      }
    }
  }
</script> 

父组件

<template>
    <div>
    <my-dialozg @close-dialog="visible = false" :visible="visible"><my-dialog>
    </div>
</template>

在对话框组件上设置事件侦听器close-dialog,并将您作为道具传递的数据属性visible设置为false。您可以如上所示内联执行此操作或将其提取到方法中

答案 1 :(得分:1)

在vuejs中,子组件不能直接修改parents属性。

您可以使用事件/事件侦听器。但由于你的例子很简单,你不需要为此事件。

演示:https://jsfiddle.net/samayo/943bx5px/28/

相反,您可以将支柱可见性传递给组件:visisble="visible",并将状态更改视为:

watch: {
  visible (val) {
    if(!val) {
        // close
    }else{
        open
    }
  }
}

现在,如果visisble从父级切换为false,则您的模态将不可见。