簡體   English   中英

當我嘗試在Vue.js中使用作用域插槽時失敗

[英]I am failing when I try to use scoped slots in Vue.js

我已經閱讀了所有教程,vue.js手冊並觀看了視頻教程,但仍然無法使作用域插槽對我有用。 下面是我一直在測試的最少代碼。 我顯然錯過了一些東西,但是。 能夠理解這一點的人可以告訴我如何更改此代碼才能起作用。 最終,我希望能夠引用(通過ajax)內部插槽中收集的數據-最終,它將是另一個組件。

<!DOCTYPE HTML>
<html>
<head>
    <script src='https://cdn.jsdelivr.net/npm/vue/dist/vue.js'>
    </script>
    <script>
        "use strict"
        window.addEventListener('load', function () {
            Vue.component('comp-onent', {
                data:function () {
                    return {dataitem:"from the 'test' component instance"}
                },
                template:`
                    <dl>
                        <dt>From inside the 'test' component</dt>
                        <dd>{{dataitem}}</dd>
                        <dt>Rendered from the slot</dt>
                        <dd><slot :dataitem="dataitem"></slot></dd>
                    </dl>
                `
            });

            let vm = new Vue({
                el:'#vue-root',
                data:{dataitem:"from the root Vue instance"}
            });
        });
    </script>
</head>
<body>
    <div id='vue-root'>
        <comp-onent "slot-scope"="fromcomponent">
            <p>Inside 'test' invocation</p>
            <dl>
                <dt>From root instance:            </dt><dd>{{dataitem}}</dd>
                <dt>From 'test' component instance:</dt><dd>{{fromcomponent.dataitem}}</dd>
            </dl>
        </comp-onent>
        <dl><dt>Outside of 'test' invocation</dt><dd>{{dataitem}}</dd></dl>
    </div>
</body>
</html>

我考慮觸發事件以將數據傳遞到根Vue實例,但是如果我有多個<comp-onent>,則此操作將失敗,因此在這種情況下不是解決方案。

我建議從一個沒有槽的簡單工作示例開始。 試試這個玩:

 <!DOCTYPE HTML> <html> <head> <script src='https://cdn.jsdelivr.net/npm/vue/dist/vue.js'> </script> <script> "use strict" window.addEventListener('load', function () { Vue.component('comp-onent', { props: { dataitem:{ default: "from the 'test' component instance" } }, template:` <dl> <dt>From inside the 'test' component</dt> <dd>{{dataitem}}</dd> </dl> ` }); let vm = new Vue({ el:'#vue-root', data:{dataitem:"from the root Vue instance"} }); }); </script> </head> <body> <div id='vue-root'> <comp-onent dataitem="something else"></comp-onent> <comp-onent :dataitem="dataitem"></comp-onent> </div> </body> </html> 

並在另一步驟中嘗試插槽。

由於有了這個jsfiddle,我終於找到了阻止它運行的原因: https ://jsfiddle.net/dronowar/uyvmtmrt/ slot-scope必須在組件調用內的元素上定義,而不是在組件本身上定義,因此

<comp-onent slot-scope="comp">
    <p :class="comp.compclass">something</p>
</comp-onent>

不起作用

<comp-onent >
    <div slot-scope="comp">
       <p :class="comp.compclass">something</p>
    </div>
</comp-onent>

確實有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM