vue入门——组件基础todolist

1. 以下是 todolist 的例子,没有用到组件:下面的3 会通过组件拆分todolist

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>...</head>
 4 <body> 
 5     <div id="root">
 6         <div>
 7             <input v-model="inputValue"/>
 8             <button v-on:click="submit">提交</button>
 9         </div>
10         <ul>
11             <li v-for="(item,index) in list" :key="index">{{item}}</li>
12         </ul>
13     </div>
14     <script>
15         new Vue({
16             el: "#root",
17             data:{
18                 inputValue: ' hello',
19                 list:[ ]
20             },
21             methods:{
22                 submit: function(){
23                     // var val = this.inputValue;
24                     this.list.push(this.inputValue);
25                     this.inputValue='';
26                 }
27             }
28         })
29     </script>
30 </body>
31 </html>

2. 全局组件和局部组件怎么写?

全局组件:在js中直接定义 Vue.component('组件名‘,{ 业务逻辑}),然后在body中直接使用组件名,子组件可以传参,组件中使用props去接收参数

 1 <body> 
   <ul> 2 <todo-item 3 v-for="(item,index) in list" 4 :key="index" 5 :content="item" 6 > 7 </todo-item>
   </ul>
8 </body> 9 <script> 10 Vue.component('todo-item',{ 11 props: ['content'], 12 template: '<li>{{content}}</li>' 13 }) 14 </script>

局部组件:第一步var 定义局部组件,然后在vue中注册局部组件,也就是给局部组件一个名字,html中直接通过名字调用

 1 html:
 2 <todo-item></todo-item>
 3 
 4 js:    
 5 //定义局部组件
 6 var TodoItem = {
 7         template: '<li>item</li>'
 8 }
 9 //在vue中注册组件
10 new Vue({
11     el: "#root",
12     components:{
13     'todo-item': TodoItem
14     }
15     ...
16 })

3. 将1中的todolist例子拆分成组件模式,用的全局组件,:key是v-bind的缩写

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>...</head>
 4 <body> 
 5     <div id="root">
 6         <div>
 7             <input v-model="inputValue"/>
 8             <button v-on:click="submit">提交</button>
 9         </div>
10         <ul>
11             <!-- <li v-for="(item,index) in list" :key="index">{{item}}</li> -->
12         <todo-item 
13             v-for="(item,index) in list" 
14             :key="index"
15             :content="item"
16             >
17         </todo-item>
18         </ul>
19     </div>
20     <script>
21     //全局组件
22     Vue.component('todo-item',{
23         props: ['content'],
24         template: '<li>{{content}}</li>'
25     })
26         new Vue({
27             el: "#root",
28             data:{
29                 inputValue: ' hello',
30                 list:[ ]
31             },
32             methods:{
33                 submit: function(){
34                     this.list.push(this.inputValue);
35                     this.inputValue='';
36                 }
37             }
38 
39         })
40     </script>
41 </body>
42 </html>

4:组件和vue实例的关系:

每一个组件都是一个vue实例,就是说组件中也可以包含data、methods、data、计算属性computed....,同时每一个vue实例都是一个组件

猜你喜欢

转载自www.cnblogs.com/ly2646/p/9418833.html