最近在学Vue.js,写了几个demo,最近会更新在学习和写demo时遇到的问题及解决办法。
这篇文章的信息录入demo主要用到了v-model、{{msg}}、v-on:keyup(@keyup)、v-on:click(@click)、v-for、v-show、mounted、filters、mounted,数据采用loaclStorage储存。
- <section id="app">
- <fieldset>
- <legend>填入信息</legend>
- <div>
- <label for="newName">姓名:</label>
- <!--绑定data:newPerson.name-->
- <input type="text" id="newName" v-model="newPerson.name" />
- </div>
- <div>
- <label for="newAge">年龄:</label>
- <!--绑定data:newPerson.age,按键事件-->
- <input type="text" id="newAge" v-model="newPerson.age" @keyup="addEnter($event)" />
- </div>
- <div>
- <label for="newSex">性别:</label>
- <!--绑定data:newPerson.sex-->
- <select name="newSex" id="newSex" v-model="newPerson.sex" >
- <option value="男">男</option>
- <option value="女">女</option>
- </select>
- </div>
- <div>
- <!--点击事件,插入新信息x-->
- <input type="button" id="addBtn" value="增加" @click="addPerson" />
- </div>
- </fieldset>
- <table>
- <tbody>
- <tr>
- <th>序号</th>
- <th>姓名</th>
- <th>年龄</th>
- <th>性别</th>
- <th>删除</th>
- </tr>
- <!--for循环绑定数据-->
- <tr v-for="(person,index) in people">
- <td><span>{{index+1}}</span></td>
- <td><span>{{person.name}}</span></td>
- <td><span>{{person.age | toInt}}</span></td>
- <td><span>{{person.sex}}</span></td>
- <!--点击事件,删除当前行-->
- <td><input type="button" value="×" @click="delPerson(index)" /></td>
- </tr>
- </tbody>
- </table>
- <div id="tips" v-show="isShow">暂无人员信息</div>
- </section>
- <script>
- var vm = new Vue({
- el: "#app",
- data: {
- //新填信息
- newPerson: {
- name: "",
- age: null,
- sex: "男"
- },
- //人员信息
- people: [],
- //是否显示“无数据”提示
- isShow:false
- },
- //调用vue生命周期,在模板挂载完成后执行,初始化localStorage信息
- mounted:function(){
- this.initPeople();
- },
- methods: {
- //初始人员信息,取自localStorage=>people
- initPeople:function(){
- if(localStorage.getItem("people") == null || localStorage.getItem("people") == "" || localStorage.getItem("people") == "[]"){
- this.people = [];
- this.isShow = true;
- }
- else{
- //字符串转对象
- this.people = JSON.parse(localStorage.getItem("people"));
- this.isShow = false;
- }
- },
- //增加新人员
- addPerson: function() {
- if(this.newPerson.name == ""){
- alert("姓名不能为空!")
- }
- else if (this.newPerson.age == "" || this.newPerson.age == null){
- alert("年龄不能为空!")
- }
- else if (isNaN(this.newPerson.age)){
- alert("年龄只能为数字!")
- this.newPerson.age = "";
- }
- else{
- //在末尾增加一个新人
- this.people.push(this.newPerson);
- //数组转JSON字符串
- localStorage.setItem("people",JSON.stringify(this.people));
- this.newPerson = {
- "name": "",
- age: null,
- sex: "男"
- };
- //隐藏提示
- this.isShow = false;
- }
- },
- //回车触发添加新人
- addEnter:function(eve){
- if(eve.keyCode == 13){
- this.addPerson();
- }
- },
- //删除某一行的人
- delPerson: function(index) {
- this.people.splice(index, 1);
- //数组转JSON字符串
- localStorage.setItem("people",JSON.stringify(this.people));
- if(this.people == ""){
- this.isShow = true;
- }
- }
- },
- //过滤器,转Int
- filters: {
- toInt(val) {
- return parseInt(val)
- }
- }
- })
- </script>