登录
首页 >  文章 >  前端

Vue JS(提供、注入)

来源:dev.to

时间:2024-12-14 20:39:40 251浏览 收藏

推广推荐
免费电影APP ➜
支持 PC / 移动端,安全直达

最近发现不少小伙伴都对文章很感兴趣,所以今天继续给大家介绍文章相关的知识,本文《Vue JS(提供、注入)》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

我们使用 provide 和 inject 将数据从父元素直接传输到任何子元素,在这段代码中我将向您展示如何使用它们

<template>
    <h1>parent component</h1>
<div class="wrapper">
    <h1>{{ user }}</h1>
    &lt;input type=&quot;text&quot; placeholder=&quot;enter username&quot; v-model=&quot;user.name&quot;&gt;
    <componentd :user="user"/>
</div>
</template>

import {reactive,provide} from "vue";


const user=reactive({
name:"jahongir",
age:30,
})

provide("user", user)
<template>
    <div>
        <div class="child-element">
            <h1>d component</h1>
            <h2>{{ user }}</h2>

        </div>
    </div>
</template>

<script setup>

import {inject} from "vue";

const user=inject("user");

结果是

Vue JS(提供、注入)

总的来说,我们所做的是

- import {provide} from "vue"; provide imported by vue
- import {reactive} from "vue"; reactive imported by vue
- const user=reactive({name:"jahongir",age:30,}) reactive object created 
- provide("user", user); in this case, first user in the string is optional name and the second value is our object that we should not be changed

在子元素中,我们接受如下所示的 inject 值

- import {inject} from "vue"; inject imported by vue;
- const user=inject("user"); user value from parent component token by veriable with any optional name. 
- for example in the above we would write any names after const but we should give inside of inject provide's first string name "user"
- <h2>{{ user }}</h2> Finally we run it so on 

谢谢大家的关注

今天带大家了解了的相关知识,希望对你有所帮助;关于文章的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>