Vue 组件的使用语法

最近在做 demo 中,没有使用到组件模板的方式,在学习插槽章节中,测试怎么将模板在本页面使用

在同一个页面中使用组件有两种方式
一种是

    Vue.component('child', {
        template:'模板内容'
    });

另一种是

1、 在需要的地方直接写模板名字
<demo1></demo1>

2、为demo1 标签写一个模板
 注意 语法必须是  template 标签,否则会被识别为html 代码,直接在页面中显示内容
另外,这个模板要写在 vue el  指定的元素(我们的demo 是 id="app")之外
<template id="child">
    模板内容
</template>

3、在 vue 中指定模板
components:{
    demo1:{
          template:'#child'
         }
    }
  • 代码
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <title>Vue 组件</title>
</head>
<body>
<div id="app">
    <div class="father">
        <h3>这里是父组件</h3>
        <child>
            <span>菜单1</span>
            <span>菜单2</span>
            <span>菜单3</span>
        </child>
    </div>
</div>

<template id="child">
    <div class="child">
        <h3>这里是子组件</h3>
        <slot></slot>
    </div>
</template>
<script>
    var vm = new Vue({
        el: '#app',
        data: {},
        components:{
            child:{
                template:'#child'
            }
        }
    });

</script>
</body>
</html>
2560633-0dde8753b7e2b15e.png
image.png
  • 另一种写发
<div id="app">
    <div class="father">
        <h3>这里是父组件</h3>
        <demo>
            <span>菜单1</span>
            <span>菜单2</span>
            <span>菜单3</span>
        </demo>
    </div>
</div>
<script>
    Vue.component('demo', {
        template: '  <div>\n' +
            '        <h3>这里是子组件标题</h3>\n' +
            '        <slot></slot>\n' +
            '    </div>'
    });
    var vm = new Vue({
        el: '#app',
        data: {},
    });
</script>

猜你喜欢

转载自blog.csdn.net/weixin_34236869/article/details/87493730