一、Vue 父组件访问子组件
1.父组件获取子组件对象
通过ref引用属性访问子组件对象
定义:
<StudentInfo :num="parentNum" ref="parentStu">StudentInfo>
使用:
- //获取子组件信息
- console.info(this.$refs["parentStu"]);

2.父组件调用子组件方法
- //父组件调用子组件方法
- this.$refs["parentStu"].change();
3.父组件传值给子组件 props (重点,可以双向绑定)
1.子组件定义
- props: {
- num: {
- type: Number,
- default: 10,
- },
- },
2.父组件使用,重点parentNum 可以实现双向绑定
- <StudentInfo :num="100">StudentInfo>
- <StudentInfo :num="parentNum" ref="parentStu">StudentInfo>
二、Vue 子组件访问父组件
1.获取父组件对象(重点,直接修改父组件变量,可以修改父组件页面展示)
this.$root
- //子组件获取父组件数据
- this.$root.parentNum += 10;
2.调用父组件方法
- //子组件调佣父组件 方法
- this.$root.parentChange();
3.给父组件传值
方案:1.调用子组件方法传值 2.使用props双向绑定传值
三、源码如下:
子组件:
- <template>
- <div>
- <p>编号:{{ stu.id }}p>
- <p>姓名:{{ stu.name }}p>
- <p>测试数字:{{ num }}p>
-
- <button @click="childClick">子组件按钮button>
- div>
- template>
-
-
- <script>
- export default {
- data() {
- return {
- stu: {
- id: 1,
- name: "张三丰",
- },
- };
- },
- props: {
- num: {
- type: Number,
- default: 10,
- },
- },
- methods: {
- change() {
- this.stu = {
- id: 2,
- name: "李四",
- };
- },
- //子组件事件
- childClick() {
- console.info(this);
- //子组件获取父组件数据
- this.$root.parentNum += 10;
-
- //子组件调佣父组件 方法
- this.$root.parentChange();
- },
- },
- mounted() {},
- };
- script>
父组件:
- <template>
- <div>
- <img alt="Vue logo" src="./assets/logo.png" />
-
- <StudentInfo :num="100">StudentInfo>
- <StudentInfo :num="parentNum" ref="parentStu">StudentInfo>
-
- <button @click="changeInfo">父组件按钮button>
-
- <p>
- parentNum:{{parentNum}}
- p>
- div>
- template>
-
- <script>
- import StudentInfo from "./components/StudentInfo.vue";
-
- export default {
- name: "App",
- components: {
- StudentInfo,
- },
- data() {
- return {
- parentNum: 88,
- };
- },
- methods: {
- changeInfo() {
- //获取子组件信息
- console.info(this.$refs["parentStu"]);
- //父组件调用子组件方法
- this.$refs["parentStu"].change();
-
- //父组件修改子组件数据
- this.parentNum = 99;
- },
- parentChange(){
- this.parentNum++;
- }
- },
- };
- script>
-
- <style>
- #app {
- font-family: Avenir, Helvetica, Arial, sans-serif;
- -webkit-font-smoothing: antialiased;
- -moz-osx-font-smoothing: grayscale;
- text-align: center;
- color: #2c3e50;
- margin-top: 60px;
- }
- style>
更多: