Hello! 欢迎来到小浪资源网!


Vue JS(提供、注入)


avatar
1986424546 2024-11-16 27

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

<template>     <h1>parent component</h1> <div class="wrapper">     <h1>{{ user }}</h1>     <input type="text" placeholder="enter username" v-model="user.name">     <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  

谢谢大家的关注

相关阅读