## 定義屬性并獲取屬性值
定義屬性我們需要用props選項,加上數組形式的屬性名稱,例如:props:[‘here’]。在組件的模板里讀出屬性值只需要用插值的形式,例如{{ here }}.
~~~javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="../assets/js/vue.js"></script>
<title>component-2</title>
</head>
<body>
<h1>component-2</h1>
<hr>
<div id="app">
<panda here="China"></panda>
</div>
<script type="text/javascript">
var app=new Vue({
el:'#app',
components:{
"panda":{
template:`<div style="color:red;">Panda from {{ here }}.</div>`,
props:['here']
}
}
})
</script>
</body>
</html>
~~~
上面的代碼定義了 panda 的組件,并用 props 設置了 here 的屬性值,在 here 屬性值里傳遞了China 給組件。
最后輸出的結果是紅色字體的 Panda from China.
## 屬性中帶’-‘的處理方式
我們在寫屬性時經常會加入’-‘來進行分詞,比如:`<panda from-here=”China”></panda>`,那這時我們在props里如果寫成`props:[‘form-here’]`是錯誤的,我們必須用小駝峰式寫法`props:[‘formHere’]`。
~~~javascript
<panda from-here="China"></panda>
var app=new Vue({
el:'#app',
components:{
"panda":{
template:`<div style="color:red;">Panda from {{ here }}.</div>`,
props:['fromHere']
}
}
})
~~~
PS:因為這里有坑,所以還是少用-為好。
### 在構造器里向組件中傳值
把構造器中data的值傳遞給組件,我們只要進行綁定就可以了。就是我們第一季學的v-bind:xxx.
我們直接看代碼:
~~~javascript
<panda v-bind:here="message"></panda>
var app=new Vue({
el:'#app',
data:{
message:'SiChuan'
},
components:{
"panda":{
template:`<div style="color:red;">Panda from {{ here }}.</div>`,
props:['here']
}
}
})
~~~