一、父子组件通信
- props/$emit
App.vue
<template>
<div id="app">
<Bar></Bar>
</div>
</template>
import Bar from './template/Bar'
Bar.vue
<template>
<Foo title='Foo to Bar' @getMessage='handleMessage'></Foo>
</template>
<script>
import Foo from './Foo'
export default {
components: {
Foo
},
methods: {
handleMessage(data) {
console.log(data)
}
},
}
</script>
Foo.vue
<template>
<div>
<h1>the message from Bar: {{ title }}</h1>
<button @click='toParent'>send</button>
</div>
</template>
<script>
export default {
name: 'Foo',
props: ['title'],
methods: {
toParent() {
this.$emit('getMessage','Foo to Bar')
}
},
}
</script>
- $refs/ref
可以获取组件实例,通过调用组件实例的方法来通信
App.vue
<template>
<div id="app">
<Bar></Bar>
</div>
</template>
<script>
import Bar from './components/Bar'
export default {
name: "App",
components: {
Bar
}
};
</script>
Bar.vue
<template>
<div>
<Foo ref='foo'></Foo>
<button ref='btn' @click='getFoo'>getfoo</button>
</div>
</template>
<script>
import Foo from './Foo'
export default {
components: {
Foo
},
methods: {
getFoo(){
// 通过ref给组件取名字,通过$refs来获取组件信息
// 获取子组件的方法来传参
this.$refs.foo.setTitle('Bar said new title')
// ref写在原生组件上,直接获取该DOM
console.log(this.$refs.btn)
}
},
}
</script>
Foo.vue
<template>
<div>
{{ newTitle }}
</div>
</template>
<script>
export default {
name: 'Foo',
data() {
return {
newTitle: ''
}
},
methods: {
setTitle(newData) {
this.newTitle = newData
},
},
}
</script>
- $parent/children
Bar.vue
<template>
<div>
<Foo></Foo>
<button @click='getFoo'>getfoo</button>
</div>
</template>
<script>
import Foo from './Foo'
export default {
components: {
Foo
},
methods: {
getFoo(){
this.$children[0].setInfo('im Bar')
}
},
}
</script>
Foo.vue
<template>
<div>
{{ title }}
<button @click='getDadInfo'>getDadInfo</button>
</div>
</template>
<script>
export default {
name: 'Foo',
data() {
return {
title: 'im Foo'
}
},
methods: {
getDadInfo(){
// 可以获取父组件信息
console.log(this.$parent)
},
setInfo(newTitle){
this.title = newTitle
}
},
}
</script>