1. 父組件向子組件傳值
- 創(chuàng)建一個兩個組件,一個父組件,一個子組件,父組件定義如下:
<template>
<div class='parent'>
<child :tableData='tableData'></child>
</div>
</template>
<script>
import child from './child.vue'
export default {
name: 'parent',
components: { child },
data () {
return {
tableData: [1,2,3,4,5,6]
}
}
}
</script>
<style>
</style>
- 子組件定義如下
<template>
<div class='child'>
<ul>
<li v-for='(item, index) in tableData' :key='index'>{{ item }}</li>
</ul>
</div>
</template>
<script>
export default {
name: 'child',
props: ['tableData'],
data () {
return {
}
}
}
</script>
<style>
</style>
2. 子組件向父組件傳值
- 創(chuàng)建一個兩個組件,一個父組件,一個子組件,子組件定義如下:
<template>
<div class='child'>
<child @click='sendDataToParent'></child>
</div>
</template>
<script>
export default {
name: 'child',
data () {
return {
tableData: [1,2,3,4,5,6]
}
},
methods: {
sendDataToParent() {
this.$emit('datas',this.$data.tableData);
}
}
}
</script>
<style>
</style>
- 父組件定義如下
<template>
<div class='parent'>
<child @datas='reciveData'></child>
</div>
<ul>
<li v-for='(item, index) in tables' :key='index'>{{ item }}</li>
</ul>
</template>
<script>
import child from './child.vue'
export default {
name: 'parent',
components: { child },
data () {
return {
tables: []
}
},
methods: {
reciveData(data) {
this.$data.tables = data
}
}
}
</script>
<style>
</style>
3. 父組件調(diào)用子組件的方法
- 創(chuàng)建一個兩個組件,一個父組件,一個子組件,父組件定義如下:
<template>
<div class='parent'>
<child ref='child'></child> // 調(diào)用子組件方法,必須加ref屬性
<p @click='getChildMethod'>調(diào)用子組件的方法</p>
</div>
</template>
<script>
import child from './child.vue'
export default {
name: 'parent',
components: { child },
data () {
return {
tableData: [1,2,3,4,5,6]
}
},
methods: {
// 此方法內(nèi),父組件內(nèi)調(diào)用子組件的方法
getChildMethod() {
this.$refs.child.sayHi();
}
}
}
</script>
<style>
</style>
- 子組件定義如下
<template>
<div class='child'>
<ul>
<li v-for='(item, index) in tableData' :key='index'>{{ item }}</li>
</ul>
</div>
</template>
<script>
export default {
name: 'child',
data () {
return {
tableData: [1,2,3,4,5,6]
}
},
methods: {
sayHi() {
console.log('hello world!')
}
}
}
</script>
<style>
</style>