1、組件的使用
<div id="app">
<!-- 3.使用組件 -->
<item></item>
</div>
<script>
/* 1.定義組件 */
var item = {
data() {
return {
msg: "hello world"
}
},
template: "<div>{{msg}}</div>"
}
var vm = new Vue({
el: "#app",
/* 2.注冊組件 */
components: {
item
}
})
</script>
2、父組件通過子組件的屬性向子組件傳遞參數
<div id="app">
<!-- 引入子組件標簽 :相當于v-bind:-->
<item v-bind:message="word"></item>
<!-- 創建item標簽,用v-bind對message的值進行動態綁定,word用于父組件,父組件對它賦值 -->
</div>
<script>
/* 子組件 */
var item = {
/* 在子組件中用props來接收父組件傳來的數據,之后展示在子組件中 */
/* 不聲明傳值的類型
props: ['message'],*/
/* 聲明傳值的類型 */
props: {
message: {
type: String
}
},
data() {
return {
msg: "hello world"
}
},
/* 模板就是頁面要顯示的數據 */
template: "<div>{{msg}}{{message}}</div>"
}
new Vue({
el: "#app",
data: {
word: "NB"
},
/* 注冊子組件 */
components: {
item
}
})
</script>
- 2-1不聲明傳值的類型
<script>
var item ={
props: ['message'],
template:"<div>{{count}}</div>"
}
</script>
- 2-2聲明傳值的類型
<script>
var item ={
props: {
message: {
type: String
}
}
template:"<div>{{count}}</div>"
}
</script>
總結:父組件向子組件傳值成功
- 子組件在props中創建一個屬性,用以接收父組件傳過來的值
- 父組件中注冊子組件
- 在子組件標簽中添加子組件props中創建的屬性
- 把需要傳給子組件的值賦給該屬性
3、子組件向父組件傳參
<div id="app">
<item @handle="handleClick"></item>
</div>
<script>
var item = {
data() {
return {
msg: "child"
}
},
template: "<div @click='handleClick'>{{msg}}</div>",
methods: {
handleClick() {
/* 給父組件自定義一個事件,向父組件傳參 */
this.$emit("handle", "hahahhaha");
}
}
}
new Vue({
el: "#app",
components: {
item
},
methods: {
handleClick(options) {
alert(options)
}
}
})
</script>
總結:子組件向父組件傳值成功
- 子組件中需要以某種方式例如點擊事件的方法來觸發一個自定義事件
- 將需要傳的值作為$emit的第二個參數,該值將作為實參傳給響應自定義事件的方法
- 在父組件中注冊子組件并在子組件標簽上綁定對自定義事件的監聽
在通信中,無論是子組件向父組件傳值還是父組件向子組件傳值,他們都有一個共同點就是有
中間介質
,子向父的介質是自定義事件
,父向子的介質是props中的屬性
。