vue-父子组件嵌套的示例

组件注册:

// 注册组件
Vue.component('my-component', {
  template: '<div>A custom component!</div>'
})

注册局部组件

var childComponent = Vue.extend({
        template: '<p>this is child template</p>'
    });
Vue.component("parent",{
        template: '<div><p>this is parent template</p><child></child></div>',
        components: {
            'child': childComponent,//child只能在父组件里使用
        }
    });

完整的html代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://npmcdn.com/vue/dist/vue.js"></script>
<title>vue-demo</title>
</head>
<body>
<h1>vue父子组件嵌套示例</h1>
<div id='app'>
  <my-component></my-component>
  <parent></parent>
</div>
</body>
<script>
// 注册组件
Vue.component('my-component', {
  template: '<div>A custom component!</div>'
})
// 子组件
var childComponent = Vue.extend({
        template: '<p>this is child template</p>'
    });
// 父组件
Vue.component("parent",{
        template: '<div><p>this is parent template</p><child></child></div>',
        components: {
            'child': childComponent,
        }
    });
new Vue({
  el: '#app',
  data: {
      }
})

</script>
</html>

注意,组件只能有一个根元素,所以最好使用一个div元素包裹组件模板,否则会提示错误:Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead.

以下是错误的:

Vue.component("parent",{
        template: '<div><p>this is parent template</p></div><child></child>',//组件有多个根元素
        components: {
            'child': childComponent,
        }
    });

也可以使用非字符串模板注册组件,如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://npmcdn.com/vue/dist/vue.js"></script>
<title>vue-demo</title>
</head>
<body>
    <h1>vue父子组件嵌套示例</h1>
<template id="child">
    <p>this is child template</p>
</template>
<template id="parent">
    <div>
        <p>this is parent template</p>
        <child></child>
    </div>
</template>
<div id="app">
    <parent></parent>
</div>
<script src="vue.js"></script>
<script>
    var childComponent = Vue.extend({
        template: '#child'
    });
    Vue.component("parent",{
        template: '#parent',
        components: {
            'child': childComponent,
        }
    });
    var app = new Vue({
        el: '#app'
    });
</script>
</body>
</html>

效果是一样的。

(完)

转载于:https://www.cnblogs.com/zhmhhu/p/7397840.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值