【Vue】组件高级用法--内联模板

内联模板

组件的模板一般都是在template选项内定义的,Vue提供了一个内联模板的功能,在使用组件时,给组件标签使用inline-template特性,组件就会把它的内容当作模板,而不是把它当内容分发,这让模板更灵活。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <title>内联模板</title>
</head>
<body>
    <div id="app">
        <child-component inline-template>
            <div>
                <h2>在父组件中定义组件的模板
                    <p>{{message}}</p>
                    <p>{{msg}}</p>
                </h2>
            </div>
        </child-component>
    </div>
    <script>
        Vue.component('child-component',{
            data: function () {
                return {
                    msg: '在子组件声明的数据'
                }
            }
        });

        var app = new Vue({
            el: '#app',
            data: {
                message: '在父组件中声明的数据'
            }
        });
    </script>
</body>
</html>

渲染结果为:

 

在父组件中声明的数据message和子组件中声明的数据msg,两个都可以渲染(如果同名,优先使用子组件的数据)。这反而是内联模板的缺点,就是作用域比较难理解,如果不是非常特殊的场景,建议不要轻易使用内联模板。

原文地址:https://www.cnblogs.com/vickylinj/p/14395840.html