1. 程式人生 > >Vue組件的通信

Vue組件的通信

周末 ext color img spa end 通過 通信 顯示

一.Vue單層組件的通信:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Vue的全局組件</title>
    </head>
<body>
    <div id="app">
        <my-div message=思思最好了></my-div>
        <my-div message=思思最棒了></my-div>
    </div>
    <!-- 定義組件 -->
    <template id="
my-div"> <div><p>{{message}}</p></div> </template> <script src="js/vue.js"></script> <script> // 創建組件 註意這裏要加#號,不然不能顯示 Vue.component(my-div, { template: #my-div, props: [message] });
// 創建vue的實例 let vm = new Vue({ el: #app, data: { name: si peng }, }); </script> </body> </html>

二.多層組件的通信:必須通過動態綁定

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8"
> <title>Vue多層組件間的通信</title> </head> <body> <div id="app"> <my-parent :imgsrc="img" :title="title"></my-parent> </div> <!-- 子組件1 --> <template id="my-image"> <img src="imgsrc" width="200"> </template> <!-- 子組件2 --> <template id="my-title"> <he>{{title}}</he> </template> <!-- 父組件 --> <template id="my-parent"> <div> <my-child1 :imgsrc=imgsrc></my-child1> <my-child2 :title=title></my-child2> </div> </template> <script src="js/vue.js"></script> <script> // 子組件的實例 let child1 = Vue.extend({ template: #my-image, props: [imgsrc] }) let child2 = Vue.extend({ template: #my-title, props: [title] }) // 註冊父組件 Vue.component(my-parent, { props: [imgsrc, title], components: { child1: child1, child2: child2 }, template: #my-parent }) // 創建vue的實例 let vm = new Vue({ el: #app, data: { title: 思思,周末快樂啊!, img: images/3.jpeg }, }); </script> </body> </html>

Vue組件的通信