我正在使用 Vue.js 构建一个分离的应用程序,使用来自 WordPress 的 Rest API 的数据。该应用程序包括按类别排序的功能。我不能使用原始表单输入来完成此操作并仍然匹配设计,我需要使用 Vue 组件来列出类别。我遇到的问题是我无法在组件模板中填充类别的名称。
组件代码:
Vue.component( 'sort-button', {
props: ['value'],
template: `
<button class="button button-accent"
v-bind:value="value"
v-on:input="$emit( 'input', $event.target.value )"
>
<a href="#">{{ cat.name }}</a>
`
}
);
我将其显示为 DOM 内模板,如下所示:
<sort-button v-for="cat in portfolioCats"></sort-button>
如果我将模板的 a 标签内容保留为静态或空白,这将遍历每个类别并给我一个相应的按钮。但是,如果我使用 {{ cat.name }} mustache ,则会出错,因为未定义 cat。
我的问题:如何让模板在 for 循环的上下文中识别 cat?请注意,我希望这是一个可重用的组件,我可以将其插入站点内的其他 Vue 实例。
谢谢!
最佳答案
您需要将变量 cat 作为 prop 传递。
<sort-button v-for="cat in portfolioCats" :cat="cat"></sort-button>
并将其添加到 props 数组中。
props: ['value', 'cat']
关于javascript - Vue.js 组件中的动态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53365907/