1、props和$emit(子触发父)、ref(父调用子)
- 父组件 给 子组件 数据传递,一般使用 props 关键字。
- 子组件 给 父组件 传递数据,一般使用 $emit 方式触发 父组件 的事件;因为 子组件 是 不能直接修改 props 中的值(即 父组件 传递的值)的,若需要修改,则要通过触发 父组件 的事件,告知父组件进行修改。
- 父组件 直接调用 子组件 的方法,可用 $refs 获取到子组件的实例,从而调用其方法
- 示例代码
// Parent.vue
<template>
<div>
<span>我是Parent组件</span>
<Child ref="child" :parentValue="value" @emitEdit="edit"></Child>
</div>
</template>
<script>
import Child from "./Child.vue";
export default {
components: { Child },
data() {
return {
value: "我是父组件"
}
},
methods: {
pFn() {
console.log("我是父组件的方法");
// 调用子组件的方法
this.$refs.child.cFn();
},
// 子组件触发,修改 value 的值
edit(msg) {
this.value = msg;
}
}
}
</script>
// Child.vue
<template>
<div>
<span>我是Child组件</span>
<span>父组件传的值:{{this.parentValue}}</span>
<button @click="editParentValue">修改 parentValue</button>
</div>
</template>
<script>
export default {
props: {
parentValue: String
},
methods: {
cFn() {
console.log("我是子组件的方法");
}
editParentValue() {
this.$emit("emitEdit", "子组件修改了我");
}
}
}
</script>