vue父组件调用子组件中的方法、值的几种方式

2023-11-09

1. ref

直接在父组件内部给子组件标签添加ref属性,然后通过ref属性来调用子组件的方法。

父组件
// Parent.vue

<template>
  <div>
    <button @click="handleClick">按钮</button>
    <Child ref="child"></Child>
  </div>
</template>

<script>
import Child from './components/child.vue'
export default {
  name: "Father",
  components: {
    Child,
  },
  methods: {
    handleClick() {
      this.$refs.child.sing()
    },
  },
}
</script>

<style scoped lang="scss">
</style>
子组件
// Child.vue

<template>
  <div>
    <p>我是子组件</p>
  </div>
</template><script>
export default {
  name: "Child",
  methods: {
    sing() {
      console.log('使用refs直接调用子组件方法')
    },
  },
}
</script>

<style scoped lang="scss">
</style>

2. $children

在父组件的方法中,通过 $children 属性来访问子组件实例,并调用子组件的方法,返回的是一个存放所有子组件的数组。

父组件
// Parent.vue

<template>
  <div>
    <button @click="handleClick">点击我调用子组件方法</button>
    <Child ref="child"></Child>
  </div>
</template>

<script>
export default {
  methods: {
    callChildMethod() {
      const childComponent = this.$children[0];
      childComponent.childMethod();
    }
  }
}
</script>

<style scoped lang="scss">
</style>
子组件
// Child.vue

<template>
  <div>
    <p>我是子组件</p>
  </div>
</template><script>
export default {
  name: "Child",
  methods: {
    childMethod() {
      console.log('使用$children直接调用子组件方法')
    },
  },
}
</script>

<style scoped lang="scss">
</style>

3. $emit $on

父组件
// Parent.vue

<template>
  <div>
    <button @click="handleClick">点击我调用子组件方法</button>
    <Child ref="child"></Child>
  </div>
</template><script>
import Child from './components/child.vue'
export default {
  components: {
    Child,
  },
  methods: {
    handleClick() {
      this.$refs.child.$emit("sing")	//子组件里$on中的名字
    },
  },
}
</script>

<style scoped lang="scss">
</style>
子组件
// Child.vue

<template>
  <div>
    <p>我是子组件</p>
  </div>
</template><script>
export default {
  mounted() {
    this.$nextTick(function () {
      this.$on('sing', function () {
        console.log('$emit配合$on实现调用子组件方法')
      })
    })
  },
}
</script>

<style scoped lang="scss">
</style>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

vue父组件调用子组件中的方法、值的几种方式 的相关文章

随机推荐