javascript - Vue.js:根据子组件的状态禁用父组件上的按钮

标签 javascript vue.js vuejs2

我已阅读有关亲子沟通的文档。我了解子级通过发出事件与父级进行通信,并且父级组件将 props 传递给子级组件。

我正在努力将这个原则应用到我的项目中:

我有一个 Survey包含多个页面的组件。我正在使用 vswipe 为页面实现 slider (https://github.com/wangdahoo/vswipe) 每个<swipe-item>包含 QuestionGroup组件又包含多个 Questions .

其中一些问题是必需的。

如何根据 Survey 的状态禁用/启用 vswipe 下一个和上一个按钮(包含在父 questions 组件中)在当前显示的QuestionGroup组件?

最佳答案

可能有点痛。您可以考虑使用 VueX以获得更优雅的图案。

顺便说一句,你在问题中说了一切。只需使用事件在 child 与 parent 之间进行交流。

这是一种方法:

Vue.component('Question', {
  template: `<div>
        {{ name }}:
        <input type="text" 
          @input="toogleFilled($event.target.value)">
        </input>
    </div>`,
  props: ['name'],
  methods: {
    toogleFilled(inputValue) {
      // Emit name of the component and true if input is filled...
      this.$emit('filled', this.name, !!inputValue.length);
    }
  }
});

Vue.component('QuestionGroup', {
  template: `<div>
        <template v-for="(q, key) in questions">
          <question :name="key" @filled="toogleReady">
          </question>
        </template>
    </div>`,
  data() {
    return {
      // Each key will be the name of the question 
      // Each value will be if it's filled or not
      questions: {
        'Question1': false,
        'Question2': false
      }
    };
  },
  methods: {
    toogleReady(name, filled) {
      this.questions[name] = filled;

      // Check if each question is filled, if yes, emit true
      if (filled && Object.values(this.questions).every(q => q)) {
        this.$emit('readyToSwipe', true);
      } else {
        this.$emit('readyToSwipe', false);
      }
    }
  }
});

Vue.component('Survey', {
  template: `<div>
    	<button :disabled="isDisabled">I'm doing nothing</button>
        <question-group @readyToSwipe="toogleDisabled"></question-group>
    </div>`,
  data() {
    return {
      isDisabled: true
    };
  },
  methods: {
    toogleDisabled(ready) {
      // Disable the button if the question-group is not ready
      this.isDisabled = !ready;
    }
  }
});

new Vue({
  el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>

<div id="app">
  <survey></survey>
</div>

关于javascript - Vue.js:根据子组件的状态禁用父组件上的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44526817/

相关文章:

javascript - 如何在angularjs中提交后隐藏表单

vue.js - 将 vuetify v-autocomplete 设置为空白

javascript - Vue.js 有时无法加载组件

javascript - Vue - 在使用 ace-editor 的用户定义组件上应用 "v-model"

vue.js - 删除 Nuxt/Vue 中的事件监听器

javascript - AngularJS ng-repeat-start ng-repeat-end with table 和 rowspan

javascript - Angular 2 中的异步等待

javascript - 我想使用此代码链接到另一个页面,并使用从当前页面获取的 id

typescript - Vue/Typescript,获取模块 '"*.vue"' 没有导出成员

node.js - Firebase 身份验证网页 : Logout with page reload