<template id="MyCpn"> <div> <h2>組件數據的存放 </h2> <p>{{title}}</p> </div> </template> <script> Vue.component('cpn', { template: '#MyCpn', data() { return { title: '我是組件中的專屬數據' } } // 組件是一個單獨模塊的封裝:這個模塊有本身的HTML模板,也有data數據。 })
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="../js/vue.js"></script> </head> <div id="app"> <cpn></cpn> </div> <body> <template id="MyCpn"> <div> <h2>組件數據的存放 </h2> <p>{{title}}</p> </div> </template> <script> Vue.component('cpn', { template: '#MyCpn', data() { return { title: '我是組件中的專屬數據' } } // 組件是一個單獨模塊的封裝:這個模塊有本身的HTML模板,也有data數據。 }) let vm = new Vue({ el: '#app', data: () => ({ title: "我是頂層Vue實例中的數據,外部組件能訪問個人數據嗎?" }) }) </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="../js/vue.js"></script> </head> <div id="app"> <cpn></cpn> <cpn></cpn> <cpn></cpn> </div> <body> <template id="MyCpn"> <div> <h2>當前計數:{{content}}</h2> <button @click="res">-</button> <button @click="add">+</button> </div> </template> <script> Vue.component('cpn', { template: '#MyCpn', data() { return { content: 0 } }, methods: { add() { this.content++ }, res() { this.content-- } } }) let vm = new Vue({ el: '#app', data: () => ({ title: "我是頂層Vue實例中的數據,外部組件能訪問個人數據嗎?" }) }) </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="../js/vue.js"></script> </head> <div id="app"> <cpn></cpn> <cpn></cpn> <cpn></cpn> </div> <body> <template id="MyCpn"> <div> <h2>當前計數:{{counter}}</h2> <button @click="res">-</button> <button @click="add">+</button> </div> </template> <script> const obj = { counter: 0 } Vue.component('cpn', { template: '#MyCpn', data() { return obj }, methods: { add() { this.counter++ }, res() { this.counter-- } } }) let vm = new Vue({ el: '#app', data: () => ({ title: "我是頂層Vue實例中的數據,外部組件能訪問個人數據嗎?" }) }) </script> </body> </html>