Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vue教程17:组件间通信之一:通过组件实例通信 #18

Open
chencl1986 opened this issue Mar 18, 2019 · 0 comments
Open

Vue教程17:组件间通信之一:通过组件实例通信 #18

chencl1986 opened this issue Mar 18, 2019 · 0 comments

Comments

@chencl1986
Copy link
Owner

阅读更多系列文章请访问我的GitHub博客,示例代码请访问这里

该节教程代码可通过npm start运行devServer,在http://localhost:8080/查看效果

父级获取子级实例实现通信

代码示例:/lesson17/src/components/parent.js,/lesson17/src/components/child.js

在父组件引用子组件时,给子组件设置ref="child"属性,父组件就可以通过this.$refs.child获取到子组件实例。
此时父组件就可以通过直接修改子组件的属性this.$refs.child.num1++,或者调用子组件方法this.$refs.child.add(),实现子组件属性变化。

子级获取父级实例实现通信

代码示例:/lesson17/src/components/parent.js,/lesson17/src/components/child.js

父组件将实例this,通过props属性parent传递给子组件。
此时子组件就可以通过直接修改父组件的属性this.parent.num1++,或者调用子组件方法this.parent.add(),实现子组件属性变化。

parent组件代码:

export default Vue.component('parent', {
  data() {
    return {
      num1: 0,
      num2: 0,
    };
  },
  components: {
    Child
  },
  methods: {
    add() {
      this.num2++
    },
    addChild1() {
      this.$refs.child.num1++
    },
    addChild2() {
      this.$refs.child.add()
    },
  },
  template: `
    <div>
      <div>父级
      num1:{{num1}}
      num2:{{num2}}
      <br/><input type="button" value="子级num1 +1" @click="addChild1" /><br/><input type="button" value="子级num2 +1" @click="addChild2" /></div>
      <child ref="child" :parent="this"></child>
    </div>
  `
});

child组件代码:

export default Vue.component('parent', {
  props: ['parent'],
  data() {
    return {
      num1: 0,
      num2: 0,
    };
  },
  methods: {
    add() {
      this.num2++
    },
    addParent1() {
      this.parent.num1++
    },
    addParent2() {
      this.parent.add()
    },
  },
  template: `
    <div>
      子级
      num1:{{num1}}
      num2:{{num2}}
      <br/><input type="button" value="父级num1 +1" @click="addParent1" />
      <br/><input type="button" value="父级num2 +1" @click="addParent2" />
    </div>
  `
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant