Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
979 views
in Technique[技术] by (71.8m points)

vue3.0如何动态的改变子组件的属性

最近在写vue3.0,试试组件库,但是发现现在没有this.$children了,依赖注入也只能在setup里面进行...我想问问3.0的话,像这种代码怎么实现呢

methods: {
            updateChildren () {
                this.$children.forEach((child) => {
                    child.separator = this.separator;
                });
            }
        },
        watch: {
            separator () {
                this.updateChildren();
            }
        }

就例如我页面有个按钮,初始化的时候依赖注入是可以的,但是当我点按钮改子组件属性的时候,应该怎么动态改呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

就是要实现组件通信吧。
可以使用provide/inject
父组件:

import { provide, ref } from 'vue'
....

setup() {
    const separator = ref(true)
    provide('separator', separator)
    const changeSeparator = () => {
        separator.value = !separator.value
    }
    return {
        changeSeparator // 提供给按钮调用
    }
}

子组件:

import { inject, Ref } from 'vue'
...
setup() {
  const separator = inject<Ref<boolean>>('separator')
  return { separator }
}

也可以使用props/$emit
父组件:

<component :separator="separator"></component>
...
import { provide, ref } from 'vue'
....
setup() {
    const separator = ref(true)
    const changeSeparator = () => {
        separator.value = !separator.value
    }
    return {
        separator,
        changeSeparator // 提供给按钮调用
    }
}

子组件:

<template>
    {{separator}}
<template>
props: {
    separator: {
      type: Boolean,
      default: true
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...