1. 程式人生 > >Vue- 元件與props屬性的用法

Vue- 元件與props屬性的用法

在 Vue 裡,一個元件實質上是一個擁有預定義選項的一個 Vue 例項:(單獨測試的時候記得new Vue()渲染)

// Define a new component called todo-itemVue.component('todo-item', { template: '<li>This is a todo</li>'})

現在你可以在另一個元件模板中寫入它:

<ol> <!-- Create an instance of the todo-item component --> <todo-item></todo-item
>
</ol>

但是這樣會為每個 todo 渲染同樣的文字,這看起來並不是很酷。我們應該將資料從父作用域傳到子元件。讓我們來修改一下元件的定義,使得它能夠接受一個 prop 欄位(屬性):

props 把資料傳給子元件!!!

“prop” 是元件資料的一個欄位,期望從父作用域傳下來。子元件需要顯式地用 props 選項 宣告 props:


Vue.component('todo-item', { // The todo-item component now accepts a // "prop", which is like a custom attribute. // This prop is called todo.
props: ['todo'], template: '<li>{{ todo.text }}</li>'})

現在,我們可以使用 v-bind 指令將 todo 傳到每一個重複的元件中:

<div id="app-7"> <ol> <!-- Now we provide each todo-item with the todo object --> <!-- it's representing, so that its content can be dynamic --> <todo-item
v-for="item in groceryList" v-bind:todo="item">
</todo-item> </ol></div>
Vue.component('todo-item', { props: ['todo'], template: '<li>{{ todo.text }}</li>'})var app7 = new Vue({ el: '#app-7', data: { groceryList: [ { text: 'Vegetables' }, { text: 'Cheese' }, { text: 'Whatever else humans are supposed to eat' } ] }})
  1. Vegetables
  2. Cheese
  3. Whatever else humans are supposed to eat