Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k 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 Reply

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
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...