1. 父组件向子组件传递
<template>
<div id="app">
<h1>This is Parent component</h1>
<Child :parent-word='msg'></Child>
</div>
</template>
<script>
import Child from "./components/Child.vue";
export default {
name: "parent",
data() {
return {
msg: "Hello,my son"
};
},
components: {
Child
}
};
</script>
<template>
<div>
I'm Child component.
<p>parent's word:{{parentWord}}</p>
</div>
</template>
<script>
export default {
name: "son",
props: ["parent-word"],
data() {
return {
msg: "Hello,my son"
};
}
};
</script>
- 以上实现从父组件传递parentWord的消息到子组件,子组件接收并显示
- 这里需要注意如果是驼峰写法的变量的话,在传递的时候要使用-连接,如:parent-word,在子组件生命注册的时候也是使用parent-word,使用的时候可以使用驼峰写法
2. 子组件像父组件传递
<template>
<div id="app">
<h1>This is Parent component</h1>
<Child @childEvent='listentToChild'></Child>
<p>child's word:{{childWord}}</p>
</div>
</template>
<script>
import Child from "./components/Child.vue";
export default {
name: "parent",
data() {
return {
childWord: ""
};
},
components: {
Child
},
methods: {
listentToChild(data) {
this.childWord = data;
}
}
};
</script>
<style>
</style>
<template>
<div>
I'm Child component.
<button @click="greet">问候爹地</button>
</div>
</template>
<script>
export default {
name: "son",
methods:{
greet(){
this.$emit("childEvent",'Hello!Mammy')
}
}
};
</script>
``
- 父组件通过@childEvent='listentToChild'注册一个方法监听子组件传递过来的消息
- 子组件通过 this.$emit("childEvent",'Hello!Mammy')方法向父组件传递消息。this.$emit中的第一个参数正是@childEvent='listentToChild'中的childEvent