14.Vue - 单页面应用Demo1

想要实现的效果

  • 通过v-for展示列表数据
  • 点击每一项列表,加上蓝色背景颜色 ,通过 :class="{active: current == index}"
  • 选中当前项,增加蓝色背景,点击添加按钮,会在下方新增一条列表,内容就是当前项的值,然后当前项蓝色背景取消

单页面Vue应用构建步骤

先随便建一个文件夹
在这个文件夹内新建一个vue文件,比如叫test.vue
在这里插入图片描述
命令行进入这个文件夹,输入 vue serve test.vue
可能会提示下图,没关系,是因为没有安装什么东西,按着提示安装即可,然后再输入 vue serve test.vue
在这里插入图片描述
vue serve test.vue 执行成功之后,会提示如下图
在这里插入图片描述
复制这个网址 http://localhost:8080/,在浏览器中打开即可,效果如下图

在这里插入图片描述

完整代码

<template>
    <div>
        <ul>
            <li v-for="(item,index) in list"
                @click="choose(index)"
                :class="{active: current == index && current !== ''}"
                :key="index">{{item}}
            </li>
        </ul>
        <button @click="add()">添加</button>
        <ul>
            <li v-for="(item,index) in target"
                :key="index">{{item}}
            </li>
        </ul>
    </div>
  
</template>

<script>
export default {
    name: 'test',
    data() {
        return{
            current: '',  //data内部的return内部每一行要写逗号分隔
            list: [1,2,3,4,5,6,7,8,9],  //data内部的return内部每一行要写逗号分隔
            target: []   //data内部的return内部每一行要写逗号分隔
        }
    },
    methods: {
        choose(index){
            this.current = index
        },
        add(){
            if(this.current === ''){return}  //methods内部的add()方法内部每一行不用写逗号分隔
            this.target.push(this.list[this.current])   //methods内部的add()方法内部每一行不用写逗号分隔
            this.current = ''   //methods内部的add()方法内部每一行不用写逗号分隔
        }
    }
}
</script>

<style>
    .active{
        background-color: blue
    }
</style>

页面效果

在这里插入图片描述
点击添加按钮后

在这里插入图片描述

发布了42 篇原创文章 · 获赞 0 · 访问量 4103

猜你喜欢

转载自blog.csdn.net/weixin_43975052/article/details/100902326