文章目錄
一、Vue項目安裝
1.安裝依賴
cnpm i -g @vue/[email protected]
cnpm i -g @vue/[email protected]
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>
預覽: