vue起步:制作todolist

第一步:简易的todolist

  <div id="app">
    <input type="text" v-model="inputValue">
    <button v-on:click="upData">提交</button>
    <ul>
      <li v-for='item in list'>{{item}}</li>
    </ul>
  </div>

vue中使用双大括号{{}}进行插值

  var app = new Vue({
      el: '#app',
      data: {
        list: [],
        inputValue: ''
      },
      methods: {
        upData: function(){
          this.list.push(this.inputValue)
          this.inputValue = ''
        }
      }
    })

初始化vue并实现添加后清空input框

第二部:使用全局组件改写

  <div id="app">
    <input type="text" v-model="inputValue">
    <button v-on:click="upData">提交</button>
    <ul>
      <todo-item 
        v-bind:content='item'
        v-for='item in list'>
      </todo-item>
    </ul>
  </div>

使用Vue.component实现全局组件,其中第一个参数是组件名(不要使用驼峰命名,在html中会被转化为短横线,所以直接使用短横线更好

    Vue.component('todo-item', {
      props: ['content'], // 这里子组件接收父组件传的值,通过v-bind绑定的父组件中item
      template: '<li>{{content}}</li>'
    })

父组件向子组件传值,子组件使用props接收。在父组件中使用bind绑定需要传给子组件的值。

第三部:使用局部组件
html部分不变

    var todoItem = {
      props: ['content'],
      template: "<li>{{content}}</li>"
    }

并在实例中使用component注册使用

      // 局部注册组件
      components: {
        // “键”和“值”一样时可缩写
        todoItem
      },

第四部:现在list点击删除相应项
个人理解(不一定正确):(在自定义组件中‘=’前边的都是子组件中使用到的,‘=’后边的都是父组件中使用到的)

      <todo-item 
        v-bind:content='item'
        v-bind:index="index"
        @removeli="deleteLi"
        v-for='(item, index) in list'>
      </todo-item>
      <!-- 父传子需要在子组件用bind绑定 -->
      <!-- 如:父向子传递了item并在子用bind绑定 -->
    var todoItem = {
      props: ['content', 'index'],
      template: "<li @click='clickLi'>{{content}}</li>",
      methods: {
        // 这里的方法就是组件内的方法
        clickLi: function(){
          // 这里是为了触发子组件模板内事件(不能使用驼峰命名),然后触发父组件相应事件
          this.$emit("removeli", this.index)
          // 第一个参数是子组件内事件名,第二个是子组件向父组件传递的参数
          // 这里定义了父组件的事件名和传入父组件的参数
        }
      }
    }

    var app = new Vue({
      el: '#app',
      // 局部注册组件
      components: {
        todoItem
      },
      data: {
        list: [],
        inputValue: ''
      },
      methods: {
        upData: function(){
          this.list.push(this.inputValue)
          this.inputValue = ''
        },
        deleteLi: function(index){
          this.list.splice(index, 1)
        }
      }
    })
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容