props傳值(父組件->子組件)
傳遞單值
父頁面
<template>
<div>
<children name='amber'></children>
</div>
</template>
<script>
import children from '@/components/children.vue'
export default {
name: 'parent',
components:{
children
}
}
</script>
子頁面
<template>
<div>
{{name}}
</div>
</template>
<script>
export default {
name: 'children',
props: {
'name': [Number, String]
}
}
</script>
傳遞對象
父頁面
<template>
<div>
<children :pet='this.xiaobu'></children>
</div>
</template>
<script>
import children from '@/components/children.vue'
export default {
name: 'parent',
components:{
children
},
data (){
return{
xiaobu:{
name:'xiaobu',
color:'white',
age:5
},
xiaohei:{
name:'xiaohei',
color:'white',
age:3
},
}
}
}
</script>
子頁面
<template>
<div>
{{pet.name}}
{{pet.color}}
{{pet.age}}
</div>
</template>
<script>
export default {
name: 'children',
props: {
'pet': {
name: [String],
color: [String],
age: [Number]
}
}
//props:{'pet':{}} //不考慮數據類型
}
</script>
emit傳值(子組件->父組件)
子組件
<template>
<div>
<el-button @click='emitToParent'>emitToParent</el-button>
</div>
</template>
<script>
export default {
name: 'children',
methods:{
emitToParent(){
this.$emit('child-event','children param')
}
}
}
</script>
父組件
<template>
<div>
<children @child-event='parentEvent'></children>
</div>
</template>
<script>
import children from '@/components/children.vue'
export default {
name: 'parent',
components: {
children
},
methods: {
parentEvent(data) {
console.log(data);
}
}
}
</script>
ref 父組件調用子組件
父組件
<template>
<div>
<children ref='child'></children>
<el-button @click='toChild'>Do</el-button>
</div>
</template>
<script>
import children from '@/components/children.vue'
export default {
name: 'parent',
components: {
children
},
methods: {
toChild() {
let str=this.$refs.child.name//獲取子組件的值
this.$refs.child.name='cc';//更新子組件字段
this.$refs.child.show('show me !')//調用子組件方法
}
}
}
</script>
子組件
<template>
<div>
{{name}}
{{des}}
</div>
</template>
<script>
export default {
name: 'children',
data() {
return {
name: 'empty',
des:''
}
},
methods: {
show(data) {
this.des=data
}
}
}
</script>