【Vue】動態加載Html片段


在編寫Vue頁面的時候,會碰到這么一個需求。由於頁面組件比較多,不可能一次性將所有的頁面都打包,只能按需獲取相應的頁面進行顯示。

比如有一個App頁面,需要異步獲取html片段通過v-html指令加載到content這個組件中。

<div id='app'>
    <content v-html='html' />
    <input type='button' @click='appendContent' >appendContent</input>
</div>

<script type="text/x-template" id='content-template'>
    <div class='content' v-html='html'> </div>
</script>

APP JS:

var content = Vue.components('content',{
    props:['html'],
    template:'#content-template'
});

var app = new Vue({
    el:'#app',
    data:{
        html:''
    },
    methods:{
        appendContent:function() {
            $.ajax({
                type:'GET',
                url:'content.html'
                success:function(response){
                    this.html = response;
                }
            });
        }
    }
});

組件

<div id='content'>
    <test1 />
    <test2 />
</div>

<script type="text/x-template" id='test1-template'>
    <div>Test 1 Component</div>
</script>

<script type="text/x-template" id='test2-template'>
    <div>Test 2 Component</div>
</script>

<script>
    var test1 = {
        template:'#test1-template'
    };

    var test2 = {
        template:'#test2-template'
    };

    var subcontent = new Vue({
        el:'#content',
        components:{
            'test1':test1,
            'test2':test2,
        }
    });
</script>

但是實際執行的時候會發現,組件沒能正確渲染。折騰了一通,發現原來v-html指令原來有個坑,插入片段的時候,js代碼無法執行

因此需要改變一下執行順序。

  • 1.將組件拆分成html和js兩個文件。
  • 2.先用ajax讀取html文件。
  • 3.成功獲取html文件后,通過require獲取js文件。

修改后的代碼如下(注:只是示例,不代表能跑得通):

主界面 html
<div id='app'>
    <content v-html='html' />
    <input type='button' @click='appendContent' >appendContent</input>
</div>

<script type="text/x-template" id='content-template'>
    <div class='content' v-html='html'> </div>
</script>

主界面 js

var content = Vue.components('content',{
    props:['html'],
    template:'#content-template'
});

var app = new Vue({
    el:'#app',
    data:{
        html:''
    },
    methods:{
        appendContent:function() {
            $.ajax({
                type:'GET',
                url:'content.html'
                success:function(response){
                    this.html = response;
                    require(['content'],function(){});
                }
            });
        }
    }
});


組件 html
<div id='content'>
    <test1 />
    <test2 />
</div>

<script type="text/x-template" id='test1-template'>
    <div>Test 1 Component</div>
</script>

<script type="text/x-template" id='test2-template'>
    <div>Test 2 Component</div>
</script>

組件 js

<script>
    var test1 = {
        template:'#test1-template'
    };

    var test2 = {
        template:'#test2-template'
    };

    var subcontent = new Vue({
        el:'#content',
        components:{
            'test1':test1,
            'test2':test2,
        }
    });
</script>

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM