как снять галочку с ответа на вопрос в детях vue от родителей - PullRequest
0 голосов
/ 18 декабря 2018

Мое приложение похоже на викторину.каждый вопрос может иметь радиокнопки, целые числа, текст и т. д. Рассмотрим вопрос с несколькими вариантами ответов.У меня есть выбор для параметров кнопки радио.в родительском Vue у меня есть кнопка сброса для каждого вопроса.Если я нажму на сброс, он должен удалить выбранный ответ для этого конкретного вопроса.

Как я могу добиться этого, если кнопка сброса находится в Parent vue, а ответ для сброса находится в дочернем Vue?

Родитель:

<template>
  <div class="inputContent">
    <p class="lead" v-if="title">
       {{title}}
    <span v-if="valueConstraints.requiredValue" class="text-danger">* . 
    </span>
   </p>
  <b-alert variant="danger" show v-else>
      This item does not have a title defined
  </b-alert>

  <!-- If type is radio -->
  <div v-if="inputType==='radio'">
    <Radio :constraints="valueConstraints" :init="init" 
           :index="index" v-on:valueChanged="sendData" />
  </div>

  <!-- If type is text -->
  <div v-else-if="inputType==='text'">
    <TextInput :constraints="valueConstraints" :init="init" v- 
        on:valueChanged="sendData"/>
  </div>

  <div class="row float-right">
    <b-button class="" variant="default" type=reset @click="reset">
    Reset1
    </b-button>
    <b-button class="" variant="default" v- 
       if="!valueConstraints.requiredValue" @click="skip">
    Skip
    </b-button>
  </div>

</div>
</template>

<style></style>

<script>
import { bus } from '../main';
import Radio from './Inputs/Radio';
import TextInput from './Inputs/TextInput';

export default {
   name: 'InputSelector',
   props: ['inputType', 'title', 'index', 'valueConstraints', 
        'init'],
   components: {
       Radio,
       TextInput,
   },
  data() {
      return {
      };
  },
  methods: {
      skip() {
         this.$emit('skip');
      },
      // this emits an event on the bus with optional 'data' param
      reset() {
         bus.$emit('resetChild', this.index);
         this.$emit('dontKnow');
      },
      sendData(val) {
         this.$emit('valueChanged', val);
         this.$emit('next');
      },
  },
};
</script>

ребенок vue:

<template>
  <div class="radioInput container ml-3 pl-3">
    <div v-if="constraints.multipleChoice">
      <b-alert show variant="warning">
        Multiple Choice radio buttons are not implemented yet!
      </b-alert>
    </div>
    <div v-else>
      <b-form-group label="">
        <b-form-radio-group v-model="selected"
                            :options="options"
                            v-bind:name="'q' + index"
                            stacked
                            class="text-left"
                            @change="sendData"
        >
        </b-form-radio-group>
      </b-form-group>
    </div>
  </div>
</template>

<style scoped>
</style>

<script>
import _ from 'lodash';
import { bus } from '../../main';

export default {
  name: 'radioInput',
  props: ['constraints', 'init', 'index'],
  data() {
    return {
      selected: null,
    };
  },
  computed: {
    options() {
      return _.map(this.constraints['itemListElement'][0]['@list'], (v) => {
        const activeValueChoices = _.filter(v['name'], ac => ac['@language'] === "en");
        return {
          text: activeValueChoices[0]['@value'],
          value: v['value'][0]['@value'],
        };
      });
    },
  },
  watch: {
    init: {
      handler() {
        if (this.init) {
          this.selected = this.init.value;
        } else {
          this.selected = false;
        }
      },
      deep: true,
    },
  },
  mounted() {
    if (this.init) {
      this.selected = this.init.value;
    }
    bus.$on('resetChild', this.resetChildMethod);
  },
  methods: {
    sendData(val) {
      this.$emit('valueChanged', val);
    },
    resetChildMethod(selectedIndex) {
      this.selected = false;
    },
  },
};
</script>

1 Ответ

0 голосов
/ 18 декабря 2018

Одним из способов было бы использование шины событий

в вашем основном js add:

//set up bus for communication
export const bus = new Vue();

в вашем родительском vue:

import {bus} from 'pathto/main.js';

// in your 'reset()' method add:
// this emits an event on the bus with optional 'data' param
bus.$emit('resetChild', data);

в вашем ребенкеVue

import {bus} from 'path/to/main';

// listen for the event on the bus and run your method
mounted(){
    bus.$on('resetChild', this.resetChildMethod());
},
methods: {
  resetChildMethod(){
    //put your reset logic here
  }
}
...