大纲
页面 引入 元件使用 Props 父传子Props 应用 (传入参数的差异 v-bind使用与否)Props 传址问题 (data初始化、computed运算)Props 新增、替换元件属性Props 进阶应用 (自定检查建构式)如何使用 Props
引入元件
注意 建议 元件名称用 多个单词组成,避免未来与 HTML 相冲 (编译时)多字词属性使用 user-name 连接,而非使用小鸵峰风格指南建立 xxx.vue档 于 src/components/HelloWorld.vue档于 views/Home.vue (页面档) 引入 // @ 会指向 /src (webpack编译时帮你导向) import HelloWorld from '@/components/HelloWorld.vue' export default{ components: { HelloWorld, // 对应引入的名称,此名称亦用于 template } }
父传子 Props
去看 Props 使用手册文章多字词属性 使用 - 串接,而非使用小鸵峰写法于 页面档 template 中使用,给予属性就会以 Props的方式往下传递 <!-- 传递纯文字 --> <HelloWorld user-name="Welcome to Your Vue.js App" /> <!-- 动态附值 利用 v-bind: 就可以带入 view 的 参数 --> <HelloWorld :user-name="post.title + ' by ' + post.author.name" />
子元件以 Props 接收尽可能的写详细,避免出错,当型别错误会被侦测到 export default { props: { src: { type: String, required: true, default: () => { message: "test"; }, // 必须符合阵列中的值 才会通过 validator: value => { ["test"].indexOf(value) !== -1; } } } }
Props 使用手册
大纲
Props 应用 (传入参数的差异 v-bind使用与否)Props 传址问题 (data初始化、computed运算)Props 新增、替换元件属性Props 进阶应用 (自定检查建构式)Props 应用 使用各型别
Vue 中文文档静态值 使用 "" 即可
动态值(有用到变数的) 使用 v-bind:title="post.title"
会被视为表达式,须要使用 v-bind者: 数字、布林、阵列、物件
布林值,预设为true(免v-bind)
<!-- 可不代入值,预设为true,不使用 v-bind --> <blog-post is-published></blog-post> <!-- --> <blog-post v-bind:is-published="false"></blog-post> <blog-post v-bind:is-published="post.isPublished"></blog-post>
Props 传入物件,不需要一个属性一个属性指定
使用 v-bind 关键字 直接带入物件 <!-- 使用 v-bind 关键字 直接带入物件 --> <blog-post v-bind="post"></blog-post> <!-- 上面的会被编译成如下 --> <blog-post v-bind:id="post.id" v-bind:title="post.title" ></blog-post>
Props 注意事项
注意 JS 利用 Props 传递 阵列、物件是传参考,因此元件改动会影响到父元件应去避免更动 Props 本身,将其利用 computed 建立新的值在做操作 // 状况1: 将 Props 设为本地要使用的值,将其用 data 保存在对其操作 props: ['initialCounter'], data: function () { return { counter: this.initialCounter } } // 状况2: 纯粹要对 Props 做运算处理,使用 computed props: ['size'], computed: { normalizedSize: function () { return this.size.trim().toLowerCase() } }
Props 参数应用
当 Props 未符合时会给予通知 (生产环境下)使用 default & validator 无法取得 data & computed 值因 Props 验证跟产生,是在 beforeCreated 阶段 (此时还未产生 data) export default { props: { msg: { // null 和 undefined 会通过任何型别 type: String, // 不建议多个 required: true, // default: "test" // default 可使用 Function 产生或直接给予值 default: function() { return { message: "hello" }; }, validator: function(value) { // 必须符合阵列中的值 才会通过 return ["success", "warning", "danger"].indexOf(value) !== -1; } } } };
Props 新增、替换元件属性
我们利用 Props 传入值 新增、替换元件的属性值 (不使用 v-bind)class 与 style 较智能,会将两者值合併若要覆盖 class, style 建议使用 props default,当有传入值时使用传入值现有一个 input (SomeForm) 已有 type & class 属性想要替换他们,我们想将其 type 改成 text & 将其 class 新增 padding
<!-- 元件 --> <input type="date" class="form-control"> <!-- 目标 --> <input name="123" type="text" class="form-control p-5"> <!-- 父元件传送 Props --> <some-form name="123" type="text" class="p-5"></some-form>
Props 进阶应用
type:String 为原生构造函式,亦可自行定义,来检测某物件是否为某建构式建造禁用特性继承 (有看没懂..)参照文档 Type Checks 或 类型检查