父組件通過 props
向子組件傳遞
父組件:
<template>
<div>
<child-component :list="testList">
</div>
</template>
<script>
import ChildComponent from '@/components/ChildComponent.vue'
export default {
name: 'home',
components: {
ChildComponent
},
data () {
return {
testList: ['line-1', 'line-2', 'line-3', 'line-4']
}
}
}
</script>
子組件:
<template>
<ul>
<li v-for="(item, index) in list" :key="index">
{{ item }}
</li>
</ul>
</template>
<script>
export default {
name: 'ChildComponent',
props: {
list: Array
}
}
</script>
這樣子組件就能接收并顯示父組件傳遞過來的數(shù)據(jù)了
子組件通過$emit
向父組件傳遞數(shù)據(jù)
子組件:
<template>
<ul>
<li v-for="(item, index) in list" :key="index" @click="handleClick(index)">
{{ item }}
</li>
</ul>
</template>
<script>
export default {
name: 'ChildComponent',
props: {
list: Array
},
methods: {
handleClick (index) {
this.$emit('childEvent', index)
}
}
}
</script>
父組件:
<template>
<div class="home">
<child-component :list="testList" @childEvent="childHandleClick"></child-component>
<div>This line's index is {{ num }}</div>
</div>
</template>
<script>
import ChildComponent from '@/components/ChildComponent.vue'
export default {
name: 'home',
components: {
ChildComponent
},
data () {
return {
testList: ['line-1', 'line-2', 'line-3', 'line-4'],
num: 'NAN'
}
},
methods: {
childHandleClick (index) {
this.num = index
}
}
}
</script>
子組件中也可以這樣簡寫:
<template>
<ul>
<li v-for="(item, index) in list" :key="index" @click="$emit('childEvent', index)">
{{ item }}
</li>
</ul>
</template>
<script>
export default {
name: 'ChildComponent',
props: {
list: Array
}
}
</script>
這樣就不用在邏輯里聲明methods
方法了, 效果是一樣的