provide-inject

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <script src="../js/vue.js"></script>
    <style>
 
    </style>

</head>
<body>
   
    <div id="root"></div>
     
    <script>  
        // provide-inject
       var app = Vue.createApp({    
            setup(){  
                const { provide, ref, readonly } = Vue
                const name = ref('Eric')
                provide('name',readonly(name))
                provide('changeName',(value) => {
                    name.value = value
                })

                const { } = Vue;
                return {  }
            },
            template:`  
                <div>
                   <child />
                </div>  
            `
        })

        app.component('child',{
            setup(){
                const { inject } = Vue
                const name  = inject('name','hello')   // 默认值是 hello
                const changeName = inject('changeName')
                const handleClick = () => {
                    changeName('Ren')
                }
                return { name,handleClick }
            },
            template:'<div @click="handleClick">{{name}}</div>'
        })
 
        app.mount('#root')

    </script>

</body>
</html>
posted @ 2021-12-14 14:00  13522679763-任国强  阅读(26)  评论(0)    收藏  举报