我有这个组件:InputField.vue
<template>
<div class="w-full">
<label class="sr-only" :for="name"></label>
<input
:placeholder="label"
:name="name"
class="border-b border-black w-full appearance-none w-full py-4 px-3 text-grey-darker leading-tight"
/>
</div>
</template>
<script>
export default {
props: {
label: {
type: String,
required: true,
default: 'label', /* <--------- Always prints default */
},
name: {
type: String,
required: true,
default: 'name', /* <--------- Always prints default */
},
},
data() {
return {}
},
}
</script>
这就是我从另一个组件中使用它的方式:
<inputField :label="Hola" :name="nombre" />
但是label
和name
始终是组件声明中定义的默认值,
知道我想念什么吗?
答案 0 :(得分:2)
我将利用Utlime编写的代码段,但该答案中存在很多问题,实际上您不能删除“:”,因为它是将其绑定为道具的东西,实际上会让组件的多个实例具有其“自己的”道具状态,如果您使用的是硬编码值,则可以像:aProp="'something'"
那样调用它,如果您要传递变量,则可以使用:aProp='variable'
正确的示例是:
Vue.component('InputField', {
template: `
<div class="w-full">
<label class="sr-only" :for="name"></label>
<input
:placeholder="label"
:name="name"
class="border-b border-black w-full appearance-none w-full py-4 px-3 text-grey-darker leading-tight"
/>
</div>
`,
props: {
label: {
type: String,
required: true,
default: 'label', /* <--------- No longer prints default if props are given */
},
name: {
type: String,
required: true,
default: 'name',
},
},
});
new Vue({
el: '#app',
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input-field :label="'Hola'" :name="'nombre'"></input-field>
<input-field :label="'Que tal Toni'" :name="'toni'"></input-field>
</div>
答案 1 :(得分:1)
您需要删除:
<inputField label="Hola" name="nombre" />
Passing Static or Dynamic Props
Vue.component('InputField', {
template: `
<div class="w-full">
<label class="sr-only" :for="name"></label>
<input
:placeholder="label"
:name="name"
class="border-b border-black w-full appearance-none w-full py-4 px-3 text-grey-darker leading-tight"
/>
</div>
`,
props: {
label: {
type: String,
required: true,
default: 'label', /* <--------- Always prints default */
},
name: {
type: String,
required: true,
default: 'name', /* <--------- Always prints default */
},
},
});
new Vue({
el: '#app',
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input-field label="Hola" name="nombre" /></input-field>
</div>