💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] >[success] # 组件概念初探,对 TodoList 进行组件代码拆分 本章节讲解了,如何使用 **v-bind指令** 以及 **创建组件**、 **使用组件** 的概念,案例如下: **index.html** ~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Todo List组件封装</title> <!-- 通过cdn方式引入vue --> <script src="https://unpkg.com/vue@next"></script> </head> <body> <div id="root"></div> </body> <script> // 创建vue实例 const app = Vue.createApp({ data(){ return{ inputValue: '', list: [ 'hello', 'word', 'dell', 'lee' ] } }, methods: { handleAddItem(){ this.list.push(this.inputValue) this.inputValue = '' } }, template: ` <div> <input v-model="inputValue"/> <button v-on:click="handleAddItem" v-bind:title="inputValue">增加</button> <ul> <todo-item v-for="(item, index) of list" v-bind:content="item" v-bind:index="index"/> </ul> </div> ` // 在标签中使用变量 }) // 定义组件同时注册组件 app.component('todo-item', { // 参数1:组件名称,参数2:组件配置 props: ['content', 'index'], // 接收父组件传值 template: '<li>{{index}} -- {{content}}</li>' }) // 1. 将template中的内容挂载到id为root的元素中 // 2. 如果有组件,必须要先注册组件,不可直接链式写法创建实例(例如:Vue.createApp(...).mount('#root')), 然后直接挂载到页面元素执行mount,载到页面元素执行mount, // 那样的话页面已经初始化完成了,component就加不进去了,所以最后mount才可以 app.mount('#root') </script> </html> ~~~