vue小记

2,755 阅读2分钟

使用vue也有一段时间了,现在对vue的一些以前没有注意到的点小结一番~

本文均采用npm安装依赖

json-server

数据存储的利器啊,我之前是采用easy-mock,遗憾的是其只能使用get请求。

json-server中 我们采用npm install -g json-server安装依赖。

在最外层文件新建mock文件,下建db.json

showImage

然后采用json格式输入数据

{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}

然后改改script,在package.json中,修改script

    "scripts": {
        "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
        "start": "node build/dev-server.js",
        "build": "node build/build.js",
        "mock": "json-server mock/db.json --port 9092",
        "mockdev": "npm run mock & npm run dev"
    },

你可以用npm run dev打开项目npm run mock打开json-server,npm run mockdev两个一起打开~~

在localhost9092可以看到我们的mock数据,端口地址可以在port后面改

localhost:9092

要对数据进行操作,需设置我们的基地址

let baseUrl = 'http://localhost:9092'; 

配合axios使用,即可对数据进行增删改查

import axios from 'axios'
export default async(url = '', data = {}, type = 'GET', method = 'fetch') => {
	type = type.toUpperCase();
	url = baseUrl + url;

	if (type == 'GET') { // search
		try {
            var res = await axios.get(url)
            return res
        } catch (error) {
            console.error(error)
        }
	} else if(type == 'PUT') { // edit
		try {
            await axios.put(url,data.data)
        } catch (error) {
            console.error(error)
		}
	} else if(type == 'POST') { // add
		try {
			await axios.post(url,data.data)
        } catch (error) {
            console.error(error)
		}
	} else if(type == 'DELETE') { // delete
		try {
            await axios.delete(url,data.data)
        } catch (error) {
            console.error(error)
		}
	}
}

比如我们要对数据中的posts进行get操作,只需在基地址后加上/posts,而若是要对其中的id为1的进行操作,则在基地址后加上/posts/1

👍

vuex

使用vuex的时候参照了github的vue大项目elm,觉得这种数据分离的方式特别好,推荐给大家

首先安装依赖npm install vuex --save

新建文件夹store,下建index.jsmutation.js,这里我只建了mutation.js,原版还有getter.jsaction.js,但因为项目中没用到,故没有建。。。

mulu

index.js

import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'

Vue.use(Vuex)

const state = {
    example: ''
}


export default new Vuex.Store({
    state,
    mutations
})

mutation.js

export default {
    setExample (state, newData) {
        state.example = newData
    }
}

从而在我们的工程文件中,引入相应的函数传入相应的数据即可

helloWorld.vue

...mapMutations([
    'setExample'
]),
    async initData(){ // 异步大法好
        let res = await getData();
        this.setExample(res.data)
        this.data = res.data;
    },

service/getData.js

import fetch from '../config/fetch'

export const getData = () => fetch('/posts', {
});

最后,项目结构是酱紫的

project

还有一点点。。。

项目中还用到了html转pdf,放github上了,感兴趣可以看一下~

感谢你的阅读,希望你哈皮每一天