vue 在项目开发中常遇到的组件之间的通信 小结
本博客主要是归类一下vue组件之间的通信交流,即:父组件如何调用子组件中声明的变量/函数 和 子组件中如何调用父组件中声明的变量/函数。
父组件和子组件是相互存在、相互依赖的,即是在vue文件中引入另一个文件,前者我们称之为“父组件”,而后者被引入的文件我们称之为“子组件”。
浏览前说明
本博客分为两大段,其中每一大段所列举的片段代码都是:前半段为父组件代码,后半段为子组件代码
。
(一)父组件<Father />
获取子组件<Children />
中声明的变量/函数
- 父组件先通过
ref
标记子组件- 再通过
$refs
获取子组件中声明的变量、方法- 要点:
1.0
/1.1
。
<template>
<!-- 父组件: -->
<!-- 1.0 给子组件标签添加 ref 标记子组件 -->
<Children ref="childrenRef" />
</template>
<script>
import Children from 'Children'; //在父组件中引入子组件
export default {
components: {
Children
},
methods: {
fatherFuntion() {
// 1.1 通过 $refs 获取和改变变量值
console.log('获取子组件 变量childrenVariableVal 的值',this.$refs.childrenRef.childrenVariableVal);
this.$refs.childrenRef.childrenVariableVal = '在父组件中更改 childrenVariableVal 的值'; //更改子组件变量
this.$refs.childrenRef.childrenFuntion('fatherCompentValue'); //调用子组件的函数
/*
//当通过 v-for 重复引入该组件的时候,得到的是一个数组
var childrenRefs = this.$refs.childrenRef;
if(childrenRefs != null) {
for(var i = 0; i < childrenRefs.length; i++) { //当引入多个的时候
childrenRefs[i].childrenVariableVal = '在父组件中更改 childrenVariableVal 的值';
}
}
*/
}
}
}
</script>
<style></style>
<template> <!-- 子组件 Children.vue --> </template>
<script>
export default {
data() {
return {
childrenVariableVal: '子组件中的变量值'
}
},
methods: {
childrenFuntion(val) {
console.log("这是在 子组件 中声明的函数", val)
}
}
}
</script>
<style></style>
(二)在子组件中获取父组件变量和调用父组件函数
- 父组件先通过子组件标签将需要的变量和函数声明
- 子组件通过
props
接收变量,再通过this
直接调用- 子组件通过
this.$emit
直接调用父组件中的函数- 要点:
1.0
/2.0
/2.1
/2.2
。
<template>
<!-- 1.0 将变量和函数在标签中传递 v-on带出的函数请勿用 驼峰式 命名-->
<Children :fatherVariableVal="fatherVariableVal" v-on:fatherfuntion="fatherFuntion" />
</template>
<script>
import Children from 'Children'; //在父组件中引入子组件
export default {
components: {
Children
},
data() {
return {
fatherVariableVal: '子组件中的变量值'
}
},
methods: {
fatherFuntion(val) {
console.log("这是从 子组件 中传过来的变量", val)
}
}
}
</script>
<style></style>
<template> <!-- 子组件 Children.vue --> </template>
<script>
export default {
data() {
return {
childrenVariableVal: '子组件中的变量值'
}
},
props: ['fatherVariableVal'], // 2.0 通过 props 接收标量
methods: {
childrenFuntion(val) {
// 2.1 this 直接引用变量
console.log("这是在 父组件中 传递过来的变量", this.fatherVariableVal);
// 2.2 通过 this.$emit 调用函数
this.$emit("fatherfuntion", this.childrenVariableVal);
// this.$emit("fatherfuntion", '');
}
}
}
</script>
<style></style>
结束语
父组件获取子组件中声明的变量/函数
- 父组件先通过
ref
标记子组件;- 再通过
$refs
获取子组件中声明的变量、方法。
在子组件中获取父组件变量和调用父组件函数
- 父组件先通过子组件标签将需要的变量和函数声明;
- 子组件通过
props
接收变量,再通过this
直接调用;- 子组件通过
this.$emit
直接调用父组件中的函数。