数据不会根据相关道具价值进行更新

时间:2017-03-31 20:07:22

标签: vue.js

我试图使用vuejs来创建一个模态窗口并将其隐藏在putton上。 这是一些代码: 的的index.html

<table class="table">
  <tr v-for = "dream in dreams">
  ...
  <th>
    <button id="show-modal" @click="showModal = true">New Post</button>
  </th>
  </tr>
</table>
...   

<editdream v-bind:show.sync="showModal"></editdream>

在editdream.vue文件中我有:

<template>
  <div v-show="isShown" transition="modal">
  ...
  </div>
</template>

<script>
  export default {
  props: ['show'],
  methods: {

    close: function () {
        this.isShown = false;
    },

    savePost: function () {
        this.close();
    }
  },
  data: function () {
    return { isShown: this.show }
  }
}

我认为当我按下按钮然后显示&#39;道具将更新为模态窗口和相应的“isShown”#39;数据也将被更新。但我只能看到道具正在成为现实,但按下按钮时,显示仍然是假的。你能解释一下原因吗?

1 个答案:

答案 0 :(得分:1)

editdream.vue内,您已在isShown下定义data

data is set once prior to the creation of the component,因此当您点击show-modal中的index.html按钮时,它不会更新。在点击按钮之前(isShown),show会保留您在创建时设置的道具false

一个简单的解决方法是让isShown成为computed property

<template>
  <div v-show="isShown" transition="modal">
  ...
  </div>
</template>

<script>
export default {
  props: ['show'],
  methods: {
    close: function () {
        this.isShown = false;
    },
    savePost: function () {
        this.close();
    }
  },
  computed: {
    isShown: function() return {this.show};
  }
}

计算属性会主动关注this上的数据,就像您的show道具一样,因此每当show时它都会更新。