【笔记】再学JavaScript ES(6-10)全版本语法——在Vue中的实战


一、Vue项目安装

1.安装依赖

cnpm i -g @vue/cli@3.11.0
cnpm i -g @vue/cli-service-global@3.12.0

2.创建项目

vue create vue-lesson -d
cd vue-lesson

3.运行项目

npm run serve

4.安装eslint

eslint --init

会出现如下提示

? How would you like to use ESLint? To check syntax, find problems, and enforce code style
? What type of modules does your project use? JavaScript modules (import/export)
? Which framework does your project use? Vue.js
? Does your project use TypeScript? No
? Where does your code run? Browser
? How would you like to define a style for your project? Use a popular style guide
? Which style guide do you want to follow? Standard: https://github.com/standard/standard
? What format do you want your config file to be in? JavaScript
? Would you like to install them now with npm? No
cnpm i -D eslint-config-standard eslint-plugin-standard eslint-plugin-promise eslint-plugin-import eslint-plugin-node

二、本地自定义mock

新建src\mock\list.json

{
  "code": "0",
  "list": [{
    "name": "AAA",
    "addr": "北京朝阳"
  }, {
    "name": "BBB",
    "addr": "北京海淀"
  }]
}

新建src\mock\user.json

{
  "code": "0",
  "user": [{
    "name": "AAA",
    "addr": "北京朝阳"
  }, {
    "name": "BBB",
    "addr": "北京海淀"
  }]
}

新建vue.config.js

module.exports = {
  devServer: {
    proxy: {
      '/user': {
        target: 'http://localhost:8081',
        pathRewrite: {
          '/user': 'user.json'
        }
      },
      '/list': {
        target: 'http://localhost:8081',
        pathRewrite: {
          '/list': 'list.json'
        }
      }
    }
  }
}

安装http-server插件

cnpm i -g http-server

在src/mock目录下启动http-server

http-server .

启动成功后,通过项目运行地址访问:http://localhost:8080/user,出现数据说明访问成功!

三、使用axios

安装axios

cnpm i axios

在src\components\HelloWorld.vue中引入axios

import axios from 'axios'

在mounted () {}中使用axios

axios.get('/user').then(res => {
  if (res.data && res.data.code === '0') {
    console.log(res.data.user)
  } else {
    console.log(new Error('error'))
  }
})

使用解构优化:

axios.get('/user').then(res => {
  if (res.data && res.data.code === '0') {
    console.log(res.data.user)
  } else {
    console.log(new Error('error'))
  }
})

使用async/await优化

async mounted () {
  const { data } = await axios.get('/user')
  if (data && data.code === '0') {
    console.log(data.user)
  } else {
    console.log(new Error('error'))
  }
}

四、创建组件并获取展示数据

新建src\components\List.vue

<template>
    <div class="list">
        <ul>
            <li v-for="item in list" :key="item.name">
                {{item.name}}-{{item.addr}}
            </li>
        </ul>
    </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'List',
  data () {
    return {
      list: []
    }
  },
  async mounted () {
    const { data } = await axios.get('/list')
    if (data && data.code === '0') {
      this.list = data.list
    } else {
      console.log(new Error('error'))
    }
  }
}
</script>

<style scoped>
</style>

修改src\App.vue为:

<template>
  <div id="app">
    <List/>
  </div>
</template>

<script>
import List from './components/List.vue'

export default {
  name: 'App',
  components: {
    List
  }
}
</script>

<style>
</style>

查看效果:
在这里插入图片描述

五、在实际场景中使用Proxy

我们的场景是这样的:拿到一组数据,对数据可以进行升序、降序、重置三种操作,这里重点是需要对数据进行保护

新建src\mock\proxy.json

{
  "code": "0",
  "price": [13.05, 2.79, 5.6, 1.48, 45.3, 73.6]
}

修改vue.config.js

module.exports = {
  devServer: {
    proxy: {
      '/user': {
        target: 'http://127.0.0.1:8081',
        pathRewrite: {
          '^/user': 'user.json'
        }
      },
      '/list': {
        target: 'http://127.0.0.1:8081',
        pathRewrite: {
          '/list': 'list.json'
        }
      },
      '/proxy': {
        target: 'http://127.0.0.1:8081',
        pathRewrite: {
          '/proxy': 'proxy.json'
        }
      }
    }
  }
}

新建src\components\Proxy.vue

<template>
    <div class="price">
        <ul>
            <li v-for="item in price" :key="item">
                {{item}}
            </li>
        </ul>
        <button type="button" name="button" @click="up">升序</button>
        <button type="button" name="button" @click="down">降序</button>
        <button type="button" name="button" @click="reset">重置</button>
    </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'Proxy',
  data () {
    return {
      price: [],
      proxy: ''
    }
  },
  async mounted () {
    const { data: { price, code } } = await axios.get('/proxy')
    Object.freeze(price) // 冻结来保护数据
    this.proxy = new Proxy({}, {
      get (target, key) {
        if (key === 'up') {
          return [].concat(price).sort((a, b) => a - b)
        } else if (key === 'down') {
          return [].concat(price).sort((a, b) => b - a)
        } else {
          return price
        }
      },
      set () {
        return false // 不允许任何赋值操作
      }
    })
    if (price && code === '0') {
      this.price = this.proxy.default
    } else {
      console.log(new Error('error'))
    }
  },
  methods: {
    up () {
      this.price = this.proxy.up
    },
    down () {
      this.price = this.proxy.down
    },
    reset () {
      this.price = this.proxy.default
    }
  }
}
</script>

<style scoped>
    ul, li {
        list-style: none;
    }
</style>

修改src\App.vue

<template>
  <div id="app">
    <List/>
    <Proxy/>
  </div>
</template>

<script>
import List from './components/List.vue'
import Proxy from './components/Proxy.vue'

export default {
  name: 'App',
  components: {
    List, Proxy
  }
}
</script>

<style>
</style>

预览

六、实际场景中使用自定义遍历

遍历一个自定义数据结构
新建src\mock\author.json

{
  "code": "0",
  "allAuthors" {
    "fiction": ["AAA", "BBB", "CCC"],
    "science": ["DDD", "EEE", "FFF", "GGG"],
    "fantasy": ["XXX", "YYY", "ZZZ"]
  }
}

修改vue.config.js

module.exports = {
  devServer: {
    proxy: {
      '/user': {
        target: 'http://127.0.0.1:8081',
        pathRewrite: {
          '^/user': 'user.json'
        }
      },
      '/list': {
        target: 'http://127.0.0.1:8081',
        pathRewrite: {
          '/list': 'list.json'
        }
      },
      '/proxy': {
        target: 'http://127.0.0.1:8081',
        pathRewrite: {
          '/proxy': 'proxy.json'
        }
      },
      '/author': {
        target: 'http://127.0.0.1:8081',
        pathRewrite: {
          '/author': 'author.json'
        }
      }
    }
  }
}

新建src\components\Author.vue

<template>
    <div class="author">
        <h1>Authors</h1>
        <ul>
            <li v-for="item in authors" :key="item">
                {{item}}
            </li>
        </ul>
    </div>
</template>

<script>
import axios from 'axios'

export default {
  data () {
    return {
      authors: {}
    }
  },
  async mounted () {
    const { data: { allAuthors, code } } = await axios.get('/author')
    const author = new Proxy(allAuthors, {
      // 判断是否存在
      has (target, key) {
        const keys = Reflect.ownKeys(target)
        for (const item of keys) {
          if (target[item].includes(key)) {
            return true
          }
        }
        return false // ?
      }
    })
    author[Symbol.iterator] = function * () {
      const keys = Reflect.ownKeys(this).slice(0, -2) // 过滤掉后面没用的两项属性"__ob__"、Symbol.iterator
      let values = []
      while (1) {
        if (!values.length) {
          if (keys.length) {
            values = [].concat(this[keys[0]]) // values依次是["AAA", "BBB", "CCC"]、["DDD", "EEE", "FFF", "GGG"]、["XXX", "YYY", "ZZZ"]
            keys.shift() // 删除第一个元素,并将第一个元素的值返回
            // 目前的values是完整的
            yield values.shift() // 删除第一个元素,并将第一个元素的值返回
            // 目前的values是去掉第一个之后的
          } else {
            return false
          }
        } else {
          // 目前的values是去掉第一个之后的(与上面延续下来的相同),再往后是上一次else中处理后的结果
          yield values.shift() // 删除第一个元素,并将第一个元素的值返回
          // 目前的values是去掉第二个之后的,再往后继续执行else里的shift,直到values为空,继续加载下一个key对应的数组
        }
      }
      // 循环中的values.shift()实现了遍历单个元素并删除,以遍历下一个元素
    }
    console.log('EEE' in author) // true
    if (allAuthors && code === '0') {
      this.authors = author // 这里实际的执行就是在调用author[Symbol.iterator]来进行遍历赋值,最终通过this.authors整体遍历到界面
    } else {
      console.log(new Error('error'))
    }
  }
}
</script>

<style scoped>
    ul, li {
        list-style: none;
    }
</style>

修改src\App.vue

<template>
  <div id="app">
    <List/>
    <Proxy/>
    <Author/>
  </div>
</template>

<script>
import List from './components/List.vue'
import Proxy from './components/Proxy.vue'
import Author from './components/Author.vue'

export default {
  name: 'App',
  components: {
    List, Proxy, Author
  }
}
</script>

<style>
</style>

预览:
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序边界

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值