vuejs组件

<div id='root'>
  <ul>
    <todo-item></todo-item>
  </ul>
</div>
<script>
  Vue.component('todo-item',{
    template:'<li>item</li>'
  })
</script>
全局组件:上面这种组件叫做全局组件,这种组件定义好了之后,直接在任何一个地方都可以使用这个组件



<div id='root'>
  <ul>
    <todo-item></todo-item>
  </ul>
</div>
<script>
  var todoItem = {
    template:'<li>item</li>'
  }
  new Vue({
    el:'#root',
    components:{
      'todo-item':todoItem
    }
  })
</script>
局部组件,上面这种叫做局部组件,需要通过components进行注册

 

每一个组件都是一个实例,一个vue是由千千万万个实例,也就是组件组成



父组件和子组件的通信需要怎么做?
需要发布订阅模式来做这个事情,子组件注册一个事件,父组件进行监听
<div id='root'>
  <input v-model='inputValue'/>
  <button @click='handleSubmit'>提交</button>
  <ul>
    <todo-item
      v-for='(item,index) of list'
      :key='index'
      :content='item'
      :index='index'
      @delete='handleDelete'
    >
    </todo-item>
  </ul>
</div>
<script>
  Vue.component('todo-item',{
    props:['content','index'],
    template:'<li @click="handleClick">{{content}}</li>',
    methods:{
      handleClick:function(index){
        this.$emit('delete',index)
      }
    }
  })
 
  new Vue({
    el:'#root',
    data:{
      inputValue:'',
      list:[]
    },
    methods:{
      handleSubmit:function(){
        console.log(this.inputValue);
        this.list.push(this.inputValue);
        this.inputValue = '';
      },
      handleDelete:function(index){
        this.list.splice(index,1)
      }
    }
  })
</script>

 

 

posted @ 2018-09-04 21:46  wzndkj  阅读(202)  评论(0编辑  收藏  举报