Vue.js学习2

42 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue入门</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
  <div id="root">
     <div>
         <input type="text" v-model="inputValue">
         <button @click="one">保存</button>
     </div>
      <ul>
          <!--content 定义一个属性 往组件中传值-->
          <todo-item v-for="(i,index) of list" :key="index" :content="i" :index="index" @delete="deleteLi"></todo-item>
      </ul>
  </div>

</body>
<script>
    //Vue提供的创建组件的方法 通过这样方式定义的组件 叫做 全局组件
    Vue.component('todo-item',{
        //props 接收传入组件里的值
        props:['content','index'],
         //定义模板
        //每个组件也都可以绑定事件
       template: '<li @click="two" >{{content}}</li>',
        methods:{
            two:function(){
               //子组件与父组件通信 $emit 这个关键字进行 子父通信
                // 自定义一个函数 delete  父组件监听这个函数
                this.$emit('delete',this.index)
            }
        }
     });
    //定义局部组件
    // var TodoList = {
    //     template:'<li>i</li>'
    // };
    new Vue({
        el:'#root',
        //使用局部组件
        // components:{
        //     'todo-item':TodoList
        // },
        data:{
            inputValue:'',
            list:[]
        },
        methods:{
          one:function(){
              //push追加内容
              this.list.push(this.inputValue);
              this.inputValue= ''
          },
          deleteLi:function(index){
              //splice 删除方法  把传到父组件的下标 从list中删除
              this.list.splice(index,1)
          }
        }
    })


</script>
</html>