我想制作一个组件,选择组件,并使其尽可能可重用。
我添加了传递对象数组的 props 选项,我可以检索数据,但问题出在结果中。
我想添加一个传递对象键的 Prop (使其成为一个变量,因此如果我使用另一个没有相同键的对象数组,它仍然可以工作),我想在选择组件中显示 例如:
user : [
{
name : "Jo",
contact : "021"
},
{
name : "Bo",
contact : "022"
}
]
您可以选择显示姓名或联系人,但它不起作用,这是我的代码,您能帮我吗?
这是组件文件
<template>
<div>
<div>Selected : </div>
<select class="form-select">
<option v-for="(option,i) in options" :key="i">
{{ option.variable }}
</option>
</select>
</div>
</template>
组件的脚本
<script>
export default {
props: {
label : {
type : String,
default : "",
},
options : {
type : Array,
default : () => [],
},
variable : {
type : String,
default : "",
},
selected : {
type : Object,
default : {}
}
},
data () {
return{
vari : this.variable //here i tried to get the props and use it at the top but same
result
}
}
}
</script>
这就是我所说的
<template>
<div class="container">
<div class="row mt-4">
<div class="col-md-6">
<h2 class="text-left">Transaction</h2>
<div>
<base-select :options="proprietaires" :variable="nom"></base-select>
</div>
</div>
</div>
最佳答案
使用方括号代替点符号option[variable]
或option[vari]
:
Vue.component('baseSelect', {
template: `
<div>
<div>Selected : </div>
<select class="form-select">
<option v-for="(option,i) in options" :key="i">
{{ option[variable] }}
</option>
</select>
</div>
`,
props: {
label : {
type : String,
default : "",
},
options : {
type : Array,
default : () => [],
},
variable : {
type : String,
default : "",
},
selected : {
type : Object,
default : () => {}
}
},
data () {
return{
vari : this.variable
}
}
})
new Vue({
el: '#demo',
data() {
return {
proprietaires: [{name : "Jo", contact : "021"}, {name : "Bo", contact : "022"}],
nom: 'name'
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<div class="container">
<div class="row mt-4">
<div class="col-md-6">
<h2 class="text-left">Transaction</h2>
<div>
<base-select :options="proprietaires" :variable="nom"></base-select>
</div>
</div>
</div>
</div>
</div>
关于javascript - v-for 通过 props vue js 传递 key 动态渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71989502/