Vue2 模板的使用

示例一

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script type="text/javascript" src="Vue-v2.5.22.js"></script>
    <title>Title</title>
</head>
<body>
<div id="app">
    <p>123</p>
</div>
<script id="tpl" type="x-template">
    <div class="tpl-cls">
        <p>This is a tpl from script tag</p>
    </div>
</script>
<!--默認會將 template 值替換掛載元素,合併掛載元素和模板根節點的屬性,唯一屬性以模板根節點爲準,模板只能有一個根元素-->
<script type="text/javascript">
    var vm = new Vue({
        el: '#app',
        template: '#tpl'
    })
</script>
</body>
</html>

示例二

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script type="text/javascript" src="Vue-v2.5.22.js"></script>
    <title>Title</title>
</head>
<body>
<div id="app">
    <my-component title="my-title" content="my-content"></my-component>
</div>
<script type="text/javascript">
    // template 的 data 必須爲一個函數,data 與 props 不能重名,且其返回值不是原始對象,否則多個組件實例會綁定同一個對象
    var MyComponent = Vue.component('my-component', {
        props: ['title', 'content'],
        data: function () {
            return {
                desc: '123'
            }
        },
        template: '<div>\
        <h1>{{title}}</h1>\
        <p>{{content}}</p>\
        <p>{{desc}}</p>\
        <div>'
    })
    var vm = new Vue({
        el: '#app'
    })
</script>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章