【发布时间】: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的道具。这意味着模板需要<material-selectcat :subcat="(variable containing subcat)">。但是你将 prop 传递给一个什么都不做的 HTML 标签,而不是一个 vue 组件。因为 v-model 给你选择的 catId,你可以简单地通过 id 找到猫,并检查它是否有子猫 -
但
:value="cat.cat_id"也在选项内并返回一个值 -
那是 vue 为你处理表单输入绑定。 props 严格用于 vue 组件。 value 也是一个标准的 html 属性。