元件内的内容并非固定,有时候我们会透过 Ajax 捞资料回来再渲染到页面上,而通常我们捞回来的资料都会存放到 Vue 实体的 data 内,这时候元件想要读取 Vue 实体的 data 资料时,就可以使用 props 来传递
基本 props 的使用:
在 my-component 内使用 app 的 data 内 msg 的字串内容
<div id="app"> <!-- 3. 动态绑定自订的名字并跟 Vue 实体的 msg 做绑定 --> <my-component :my-title="msg"></my-component></div><script type="text/x-template" id="my-component"> <div class="card"> <!-- 2. 把自订的名字呈现在 x-template 内 --> <div class="card-title">{{ myTitle }}</div> ... </div></script><script> // 1. 先在 Vue.component() 内使用 props 并自订一个名字 Vue.component('my-component', { template: '#my-component', props: ['myTitle'], }); const app = new Vue({ el: '#app', data: { msg: 'Title', } });</script>
步骤如下:
先在 Vue.component() 内使用 props 并自订一个名字把自订的名字呈现在 x-template 内动态绑定自订的名字并跟 Vue 实体的 msg 做绑定上述是基本的 props 使用。
props 之检查型态:
有时候我们会希望从外部传递进去元件的资料,是有指定的资料型态,这个时候就需要改变 props 的写法,改成用物件,自定义传递资料的名字也需改成物件的方式
Vue.component('my-component', { template: '#my-component', props: { propA: Number, // 指定数值型别 propB: [String, Number], // 指定多种条件可以写成阵列 propC: { // 必要栏位,且限定为字串型别 type: String, required: true, }, propD: { // 指定为数字型别,若外面没有预设数字,则指定预设数字 type: Number, dafault: 100, }, propE: { // 指定为物件型别,可以为阵列或者物件,并指定预设资料 type: Object, default: function(){ return { msg: 'Hello' } } }, propF: { // 使用 validator 自订验证 validator: function(value){ // value 为传送进去的资料 // 当大于 10 的时候才会通过验证 return value > 10 } } }});
props 之传递物件:
当我们要传送到元件的资料为 Vue 实体的 data 物件格式的某个属性时,会发生什么事 ?
<my-component :count="counts"></my-component><script> Vue.component('my-component', { template: '{{ count.num }}<button @click="count.num++"></button>', props: ['count'] }); const app = new Vue({ el: '#app', data: { counts: { num: 0, } } });</script>
按照原生的 JS 语法,我们会下意识的直接用 .
来读取物件的属性,但这时候会是错误的,因为 JS 的物件传参考特性,所以即使我们使用 props 仍然会去更改到 Vue 实体的资料,那解决的方法其实前一篇也有讲到,用 function return 的方式,如下:
Vue.component('my-component', { template: '{{ newCount }}<button @click="newCount++"></button>', props: ['count'], data: function(){ return { newCount: this.count.num } }});
以上就是 Vue 实体要传递资料给元件的 props 介绍。