【问题标题】:Vue JS prop in component always undefined组件中的 Vue JS 属性始终未定义
【发布时间】:2018-01-27 08:50:45
【问题描述】:

我有一个<select> 组件。一旦我选择了一个类别,我需要获取 ID 和一个布尔值,用于检查该类别是否有子类别,如果有,我会调用 API 来获取子类别。

父模板:

<material-selectcat v-model="catId" name="category" id="selcat">
  <option 
    v-for="cat in cats" 
    :value="cat.cat_id" 
    :subcat="cat.has_subCat" 
    v-text="cat.category_name"
  ></option>
</material-selectcat>

子组件:

<template>
  <select><slot></slot></select>
</template>

<script>

    export default {

      props: ['value', 'subcat'],
      watch: {
        watcher: function() {}
      },
      computed: {
        watcher: function() {
          this.relaod(this.value);
          this.fetchSubCategories(this.value, this.subcat);
        }
      },
      methods: {
        relaod: function(value) {

          var select = $(this.$el);

          select.val(value || this.value);
          select.material_select('destroy');
          select.material_select();
        },
        fetchSubCategories: function(val, sub) {
          var mdl = this;
          var catID = val || this.value;
          console.log("sub: " + sub);

          mdl.$emit("reset-subcats");

          if (catID) {
            if (sub == 1) {
              if ($('.subdropdown').is(":visible") == true) {
                $('.subdropdown').fadeOut();
              }
            } else {
              axios.get(URL.API + '/subcategories/' + catID)
                .then(function(response) {
                  response = response.data.subcatData;
                  response.unshift({
                    subcat_id: '0',
                    subcategory_name: 'All Subcategories'
                  });
                  mdl.$emit("update-subcats", response);

                  $('.subdropdown').fadeIn();
                })
                .catch(function(error) {
                  if (error.response.data) {

                    swal({
                      title: "Something went wrong",
                      text: "Please try again",
                      type: "error",
                      html: false
                    });

                  }
                });
            }
          } else {
            if ($('.subdropdown').is(":visible") == true) {
              $('.subdropdown').fadeOut();
            }
          }
        }
      },
      mounted: function() {

        var vm = this;
        var select = $(this.$el);

        select
          .val(this.value)
          .on('change', function() {
            vm.$emit('input', this.value);
          });

        select.material_select();
      },
      updated: function() {

        this.relaod();
      },
      destroyed: function() {

        $(this.$el).material_select('destroy');
      }
    }
</script>

但是在fetchSubCategories() 函数内部,这一行总是返回undefined

console.log("sub: " + sub);

如果我在 Chrome 检查器中检查 Vue Devtools 选项卡,我可以看到所有数据都存在:

cat_id:0
category_name:"All Subcategories"
has_subCat:0

但是为什么has_subCat 不作为道具传递呢?

【问题讨论】:

  • 你在 option 上传递了 prop,而你在 select 上声明了 prop。
  • @EricGuan 抱歉我没关注?我可以读取除:subcat="cat.has_subCat" 之外的所有值
  • 您编写的代码表明material-selectcat 需要一个名为subcat 的道具。这意味着模板需要&lt;material-selectcat :subcat="(variable containing subcat)"&gt;。但是你将 prop 传递给一个什么都不做的 HTML 标签,而不是一个 vue 组件。因为 v-model 给你选择的 catId,你可以简单地通过 id 找到猫,并检查它是否有子猫
  • :value="cat.cat_id" 也在选项内并返回一个值
  • 那是 vue 为你处理表单输入绑定。 props 严格用于 vue 组件。 value 也是一个标准的 html 属性。

标签: vue.js vuejs2


【解决方案1】:

subcat 属性是undefined,因为您没有将它传递给组件。但是,subcat 属性无论如何都没有多大意义,因为您想检查 select 中每个 option 的值,这可能都不同。

如果您在组件定义中编写选项:

// child component script
props: ['value', 'options'],
// child component template
<template>
  <select>
    <slot>
      <option 
        v-for="option in options" 
        :key="option.id"
        :value="option.id" 
        :subcat="option.subcat" 
        v-text="option.text"
      ></option>
    </slot>
  </select>
</template>

然后将一个格式正确的options prop 传递给组件:

// parent component script
computed: {
  options() {
    return this.cats.map((cat) => {
      return {
        id: cat.cat_id,
        subcat: cat.has_subcat,
        text: cat.category_name
      }
    });
  }
}
// parent component template
<material-selectcat v-model="catId" :options="options" name="category" id="selcat">
</material-selectcat>

然后,您可以通过在fetchSubCategories 方法中引用options 属性来为任何选项对应的value 获取正确的subcat 值:

fetchSubCategories: function(val) {
  var mdl = this;
  var catID = val || this.value;
  var sub = (this.options.find(o => o.id === val) || {}).subcat;
  ...

在代码中定义 value 属性的原因是您在组件标签上使用了 v-model 指令。 The v-model directive is just syntactic sugar:value="something" @input="something = $event.target.value"。由于您已将 catID 指定为 v-model,因此它将作为 value 属性传递给您的组件。

【讨论】:

    猜你喜欢
    • 2019-09-08
    • 2018-01-06
    • 1970-01-01
    • 2016-05-18
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2020-11-22
    • 2021-09-14
    相关资源
    最近更新 更多