1. 程式人生 > >vue-父子組件嵌套的示例

vue-父子組件嵌套的示例

head vue clas tom script 提示 cnblogs htm style

組件註冊:

// 註冊組件
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>

效果是一樣的。

(完)

vue-父子組件嵌套的示例