組件實例的作用域是孤立的,這就意味着不能在子組件的模板內直接使用父組件的數據,要讓子組件使用父組件的數據,我們需要通過Props選項。
Prop
1、Prop是單向綁定的,也就是說當父屬性的值發生變化時,將傳遞給子組件,但是不會反過來;
2、每次父組件更新時,子組件的所有 prop 都會更新爲最新值。
<ul>
<!-- 在這裏使用我們剛纔定義的組件 -->
<todo-item
v-for="(item,index) of list"
:key="index"
//把item的值賦值給component
:content="item"
>
</todo-item>
</ul>
我們父組件中屬性要想在我們子組件中使用,需要用到prop屬性進行傳遞
Vue.component('todo-item',{
// template爲我們組件的模板
props: ['content'],
template:'<li>{{content}}</li>'
}
完整聯繫代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>vue入門</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="root">
<!-- -->
<div>
<input v-model="inputValue"/>
<button @click="submit">提交</button>
</div>
<!--循環取出item裏面的值 -->
<!-- <ul>
<li v-for="(item,index) of list" :key="index">
{{item}}
</li>
</ul> -->
<ul>
<!-- 在這裏使用我們剛纔定義的組件 -->
<todo-item
v-for="(item,index) of list"
:key="index"
:content="item"
>
</todo-item>
</ul>
</div>
<!-- 在body裏面加一個<script>標籤我們去創建一個vue的實例 -->
<script>
// 這裏我們去自定義一個組件內容(全局組件)
Vue.component('todo-item',{
// template爲我們組件的模板
props: ['content'],
template:'<li>{{content}}</li>'
}
)
new Vue({
el:"#root",//el:大意是我讓vue這個實例去接管頁面上哪個元素(vue實例去和哪個dom節點做綁定)
data:{
show:true,
inputValue:"",
list:[]
},
methods: {
submit:function(){
//當我們按下提交按鈕時,要往數據裏增加一個數據
this.list.push(this.inputValue),
this.inputValue=""
}
}
})
</script>
</body>
</html>