我们使用 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");
结果是
总的来说,我们所做的是
- 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
谢谢大家的关注
以上就是Vue JS(提供、注入)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号