下面我們來驗證下猜想:
first:定義一個parent component
<template> <p> <childOne></childOne> </p> </template> <script> import childOne from '../components/test/ChildOne' export default { name: "Parent", provide: { for: "demo" }, components:{ childOne } }
在這里我們在父組件中provide for這個變量。
second 定義一個子組件
<template> <p> {{demo}} <childtwo></childtwo> </p> </template> <script> import childtwo from './ChildTwo' export default { name: "childOne", inject: ['for'], data() { return { demo: this.for } }, components: { childtwo } } </script>
third 定義另一個子組件
<template> <p> {{demo}} </p> </template> <script> export default { name: "", inject: ['for'], data() { return { demo: this.for } } } </script>
在2個子組件中我們使用jnject注入了provide提供的變量for,并將它提供給了data屬性。
這里官網注明例子只工作在 Vue 2.2.1 或更高版本。低于這個版本時,注入的值會在 props 和 data 初始化之后得到。運行之后看下結果
相關推薦:
vue 2 使用Bus.js實現非父子組件通信
基于vue.js和webpack的Chat示例
Vue.js最佳實踐(五招讓你成為Vue.js大師)
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com