vue.js - 将 props 值传递给组件

标签 vue.js properties components

我有这个组件: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" />

但是 labelname 始终是组件声明中定义的默认值,

知道我错过了什么吗?

最佳答案

我将利用 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/

相关文章:

vue.js - 如何定位多平台-Vue CLI插件Electronic Builder

javascript - 为什么异步函数在await之后继续(在vuex中)

java - 在 spring 运行时重新加载 users.properties

javascript - 为什么在无状态函数表达式中中断 'console.log'?

asp.net-mvc - 如何为 ASP.NET MVC 开发 "shippable"组件?

jquery - Vue loader - 为所有组件全局导入 jquery

java - 如何在不使用-D语法的情况下将属性传递给JVM?

java - Properties.loadFromXML NullPointerException 与 jUnit

matrix - Maxima:简化矩阵分量

javascript - 通过单击返回错误的按钮在 Vue 中添加新的组件实例