使用vue开发web app - 2 - 创建一个列表控件

使用vue开发web app - 2 - 创建一个列表控件

课程参考视频:https://egghead.io/lessons/javascript-create-a-list-component-in-vue-js

目录

  • 目录
  • 目的
  • 步骤
  • 基本要求
  • 源码

目的:

  1. 学会使用v-for进行循环
  2. 学会使用v-on进行事件绑定
  3. 学会编写事件响应函数

步骤:

  1. 创建列表,并绑定数据
   
            <li v-for="item in items">
            
                {{ item.text }}
            li>
  1. 添加增加按钮,绑定事件,编写添加元素事件内容(addItem)
addItem: function() {
                var input = document.getElementById("itemForm");

                if (input.value != "") {
                    this.items.push({
                        text: input.value
                    })
                    input.value = "";
                }

            }
  1. 添加删除按钮,绑定事件,编写删除元素事件内容(deleteItem)
         deleteItem: function(index) {
                this.items.splice(index, 1)
            }

基本要求

  1. 了解json数据格式;
  2. 了解基本html使用;
  3. js的基础知识

源码:


<html>

<head>
    <title>title>
    
    <script src="https://unpkg.com/vue/dist/vue.js">script>
head>

<body>
    
    <div id="card">
        
        <header>{{ title }}header>

        <div>
            
            <input id="itemForm" v-on:keypress.enter="addItem" />
            
            <button v-on:click="addItem">添加人物button>
        div>
        <ul>
        
            <li v-for="(item,index) in items">
                    
                <button v-on:click="deleteItem(index)">xbutton>
                {{ item.text }}
            li>
        ul>
    div>
    <script type="text/javascript">
    var app = new Vue({
        el: "#card",
        data: {
            title: "哆啦A梦人物列表",
            items: [{
                text: "野比大雄"
            }, {
                text: "静香"
            }, {
                text: "胖虎"
            }, ]

        },
        methods: {
            addItem: function() {
                var input = document.getElementById("itemForm");

                if (input.value != "") {
                    this.items.push({
                        text: input.value
                    })
                    input.value = "";
                }

            },
            deleteItem: function(index) {
                this.items.splice(index, 1)
            }
        }
    })
    script>
body>

html>


[1]https://egghead.io/

你可能感兴趣的:(web前端)