provide and inject are methods for sharing data in Vue.js: provide() provides data in the parent component. inject() gets the data provided by the parent component in the child component. Features: Data is responsive and flows to the required location on demand without explicitly passing props.
provide and inject in Vue.js
Question: What is Vue. provide and inject in js?
Answer: provide and inject are two global methods in Vue.js, used to share data between different components.
Detailed description:
provide
## is used in the parent component to provide data to its child components. - Use the provide() method in the parent component's setup() or created() method to provide data.
- Syntax used:
- provide('propertyName', value)
inject
Use Get data from parent component in child component. - Use the inject() method in the setup() method of the subcomponent to obtain data.
- Syntax used:
- const propertyName = inject('propertyName')
Usage:
In the parent component, use the provide() method to provide data: -
<code class="javascript">// 父组件
export default {
setup() {
provide('sharedData', {
message: 'Hello, world!'
})
}
}</code>
In the child component, use the inject() method to obtain data: -
<code class="javascript">// 子组件
export default {
setup() {
const sharedData = inject('sharedData')
console.log(sharedData.message) // 输出: "Hello, world!"
}
}</code>
Features:
provide and inject allow data to flow on demand to the desired location in the component tree. - They can be used to share state, configuration items, or other data without explicitly passing props from component to component.
- The shared data is responsive, when it changes in the parent component, the child component will automatically update.
-
The above is the detailed content of Usage of provide and inject in vue. For more information, please follow other related articles on the PHP Chinese website!
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn