0
点赞
收藏
分享

微信扫一扫

依赖注入的用法

年迈的代码机器 2022-03-11 阅读 35
<!DOCTYPE html>
<html>
<div id="app">
    <parent></parent>
</div>
<script src="https://unpkg.com/vue@next"></script>
<script>
const { ref, provide, inject, onMounted } = Vue;
const app = Vue.createApp({});
const msgKey = Symbol();
const helloKey = Symbol();

app.component('parent', {
    setup() {
        const msg = ref('Java无难事');
        const sayHello = function(name) {
            console.log("Hello", + name);
        }
    provide(msgKey, msg);
    provide(helloKey, sayHello);
    return {
        msg
    }
    },
    template: '<child>'
})

app.component('child', {
    setup(){
        const message = inject(msgKey, ref('VC++ 深入详解'));
        const hello = inject(helloKey);
        onMounted(() => hello('zhangsan'));
        return {
            message
        }
    },
    template: '<p>{{ message }}</p>'
})
const vm = app.mount('#app')
</script>
</html>

举报

相关推荐

0 条评论