[英]Vue Component Conditional Creation
如果 object 变量store.plan
不为空,我想有条件地创建一个动作列表(每个动作都是一个组件),我已经尝试过v-if
它适用于渲染但不适用于创建组件。
我得到一个错误:
Uncaught (in promise) TypeError: action is undefined
可以在此处找到该组件的完整代码。
你能告诉我如何处理这个问题吗? 提前致谢。
<template>
<div class="planlist" v-if="parse">
<ul id="planOl">
<Action
v-for="action in store.plan"
:action_id="action.act_id"
:actor="action.actor"
:color="action.color"
:size="action.size"
:lego_name="action.lego"
:pick_pos="action.pick"
:place_pos="action.place"
:blocked="action.blocked"
:status="action.status"
:key="action.act_id"
/>
</ul>
</div>
</template>
<script>
import Action from '../components/Action.vue';
import { store } from '../js/store.js'
export default {
name: 'Plan',
data() {
return {
store,
}
},
computed: {
parse() {
if (store.plan.length > 0) {
return true;
}
return false;
}
},
components: {Action}
}
</script>
您是否尝试过optional chaining
:
parse() {
return store?.plan?.length > 0 ? true : false
}
不要混用 v-if 和 v-for。 尝试在您的组件周围使用 v-if 创建包装器 div:
<ul id="planOl">
<div v-if="parse">
<Action
v-for="action in store.plan"
:action_id="action.act_id"
:actor="action.actor"
:color="action.color"
:size="action.size"
:lego_name="action.lego"
:pick_pos="action.pick"
:place_pos="action.place"
:blocked="action.blocked"
:status="action.status"
:key="action.act_id"
/>
</div>
</ul>
由于语法歧义,建议不要在同一元素上同时使用v-if
和v-for
指令。
根据您的代码,计算属性parse
用于检查数组的长度。 您可以将 v-if 移动到container
元素(例如ul
)。
在模板中:
<ul id="planOl" v-if="parse">
<Action v-for="action in store.plan">...</Action>
</ul>
脚本:
computed: {
parse() {
return store.plan.length > 0 ? true : false;
}
}
store.plan
移动到计算属性以在模板和parse
属性中使用。store.plan.length
也可以完成这项工作,而不是根据条件返回 true 和 false。Action
组件之外使用v-if
,你可以使用template
来实现。 不需要额外的元素。因此,以下更改可以帮助解决问题 -
<template>
<div class="planlist">
<ul id="planOl">
<template v-if="parse">
<Action
v-for="action in plan"
:key="action.act_id"
:action_id="action.act_id"
:actor="action.actor"
:color="action.color"
:size="action.size"
:lego_name="action.lego"
:pick_pos="action.pick"
:place_pos="action.place"
:blocked="action.blocked"
:status="action.status"
/>
</template>
</ul>
</div>
</template>
<script>
import Action from "../components/Action.vue";
import { store } from "../js/store.js";
export default {
name: "Plan",
components: {
Action,
},
computed: {
// A computed property to access the plan ()
plan() {
return store.plan;
},
parse() {
/**
* 1. The plan should be available (not null or empty or undefined)
* 2. The plan should be an array so length property can be applied
* 3. If its an array then it should have data (length in other words)
*/
return this.plan && Array.isArray(this.plan) && this.plan.length;
},
},
};
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.