Как проверить дочерний компонент с помощью vue ant design? - PullRequest
0 голосов
/ 14 октября 2019

У меня есть этот компонент DynamicSelect (дочерний компонент), и я использую его в другом компоненте (родительском), но когда я пытаюсь проверить свой компонент childe, он всегда возвращает значение как нулевое, поэтому проверка всегда ложна

DynamicSelect Component:

<template>
  <a-select
    :showSearch="true"
    :placeholder=placeholder
    :value="selectedValue"
    @search="searchRegex($event)"
    @change="$emit('changed-item', setChangedItem($event))"
    @select="$emit('selected-item', setSelectedItem($event))"
    :filterOption="filterOption"
  >
    <a-select-option
      v-for="(item,idx) in dropdownData"
      :value="idx"
      :key="idx"
    >{{item.text}}</a-select-option>
  </a-select>
</template>

<script>


  export default {
    name: "DynamicSelect",
    data(){
      return{
          dropdownData: [],
          copyDropdownData:[],
          selectedValue: undefined
      }
    },
    props:{
      //Input data collection
      dataSrc:Array,

      //Placeholder for input field
      placeholder: String,

      //if true the dropdown will be automatically cleared after element selected
      resetAfterSelect: false,

      // List of id to filter the dropdown list
      lookFor:Array,

      // Data to display in the dropdown if not set,  lookFor list will be displayed
      displayedValues: Array,

      //Default Value
      defaultValues:String,

    },
    beforeMount(){
      this.checkDefaultVariable();
    },
    watch:{
      dataSrc:function(newVar,oldVar) { // watch it
        this.checkDefaultVariable()
      }
    },
    methods:{
      //Search for search term in the data collection 'lookFor' elements to set the dropdown list
      async searchRegex(term){
        if(term.length>2) {
          let searchTerm = new RegExp(term.toUpperCase());
          this.dropdownData = await this.filterData(searchTerm);
          this.copyDropdownData = JSON.parse(JSON.stringify(this.dropdownData));
        }
        else
        {
          this.dropdownData = [];
          this.copyDropdownData = [];
        }
      },

      filterData(searchTerm){
        return this.dataSrc.filter(x => {
          let filtered= [];
          for (let i=0; i<this.lookFor.length;i++){
            if(x[this.lookFor[i]])
            {
              if(searchTerm.test(x[this.lookFor[i]].toUpperCase()))
              {
                let text = '';
                if(this.displayedValues !== undefined)
                {
                  for (let k=0; k<this.displayedValues.length;k++)
                  {
                    text += x[this.displayedValues[k]];
                    if(k < this.displayedValues.length-1)
                      text += ', '
                  }
                }
                else {
                  for (let k=0; k<this.lookFor.length;k++)
                  {
                    text += x[this.lookFor[k]];
                    if(k < this.lookFor.length-1)
                      text += ', '
                  }
                }
                x.text = text;
                filtered.push(x);
              }
            }
          }
          return filtered.length>0
        });
      },

      // just a logger
      logger(event){
        console.log(event);
      },

      async checkDefaultVariable(){
        if (this.defaultValues !== '' && this.defaultValues !== undefined && this.dataSrc.length>0 ){
          // console.log('DATA',this.dataSrc);
          await this.searchRegex(this.defaultValues);
          let selected = await this.setSelectedItem(0);
          this.$emit('selected-item', selected)
        }
      },

      // return the selected Item as an Object
     setSelectedItem(id){
       // console.log('ON SELECT');
        let temp =  JSON.parse(JSON.stringify(this.dropdownData[id]));
         delete temp.text;
          if(this.resetAfterSelect)
          {
              this.dropdownData = [];
              this.selectedValue = undefined;
          }
          else {
            this.selectedValue = id;
          }

        return temp
      },

      setChangedItem(id){
        let temp =  JSON.parse(JSON.stringify(this.copyDropdownData[id]));
        delete temp.text;
        if(this.resetAfterSelect)
        {
          this.copyDropdownData = [];
          this.selectedValue = undefined;
        }
        else {
          this.selectedValue = id;
        }
        return temp
      },

      // search in the dropdown list
      filterOption(input, option) {
        let searchTerm = new RegExp(input.toUpperCase());
          if(searchTerm.test(this.dropdownData[option.key].text.toUpperCase()))
            return true;
          else {
            for(let i=0;i<this.lookFor.length;i++){
              if(searchTerm.test(this.dropdownData[option.key][this.lookFor[i]].toUpperCase()))
                return true;
              else if(i >= this.lookFor.length)
                return false;
            }
          }
      }
    }
  }
</script>

родительский компонент:

<template>

<dynamic-select
                      :dataSrc="users"
                      placeholder="Lastname, Firstname"
                      @selected-item="onSelectUser($event)"
                      @changed-item="onSelectUser($event)"
                      :lookFor="['lastname','firstname']"
                      v-decorator="['contact', {valuePropName:'selectedValue', 
                      rules: [{ required: true, 
                                validator: userExists, 
                                 message: 'Error'}]}]"
              >
</dynamic-select>

</template>

<script>
.
.
.
methods: {

userExists(rule, value, callback) {
        console.log('VALUE', value); //always undefined
        console.log('RULES',rule);
        console.log('CALLBACK',callback)
        return value !== null && value !== undefined && value.length > 2;
      },



onSelectUser(user) {
        console.log("user: " , user); // set with the selected value
       }
},
.
.
.
</script>

Я ожидаю, что дочерний компонент возвращает выбранное значение, как при отправке события, я также пытался с моделями, ноэто не помогло спасибо:)

1 Ответ

0 голосов
/ 14 октября 2019

Вы можете легко общаться между компонентами

Vue.config.debug = true;

// Parent
let App = new Vue({
  el: "#the-parent",
  
  data(){
    return{ msg: "Nothing.." };
  },
  
  methods:{
    receivedFromChild(request){
      this.msg = request;
    }
  },
  
  
  // Children
  components: {
    'children': {
      template: `
        <div><button @click="request">Send to parent!</button>` + `<input type="text" v-model="text"></div>`,
      
      props: [ 'childrenRequest' ],
      data() {
        return {
          text: 'this is value'
        }
      },
      methods: {
        request(){
          console.log('work!');
          this.$emit('received', this.text);
        }
      }
    
    }
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="the-parent">
    <h3>The children want me to say: {{ msg }}</h3>
    <children @received="receivedFromChild"></children>
</div>
...