我有这个组件: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
始终是组件声明中定义的默认值,
知道我错过了什么吗?
最佳答案
我将利用 Utlime 完成的代码片段,但该答案中存在很多问题,事实上,您不能取出“:”,因为它是将其绑定(bind)为 Prop 的东西,实际上会让组件的多个实例拥有自己的“自己”的 props 状态,如果您使用硬编码值,只需像 :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>
关于vue.js - 将 props 值传递给组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55237681/