Vant4+json+vue3 app project development notes

This chapter describes some of my experience and notes when writing the vue3 project, thank you for watching.

1. Environment construction

1-1 nodejs environment installation

https://nodejs.org/zh-cn/
insert image description here

1-2npm Taobao mirror installation

npm install -g cnpm --registry=https://registry.npm.taobao.org

1-3vite project construction

http://www.vitejs.net/

1-4 Create a vue3 project

# npm 6.x
npm init vite@latest my-vue-app --template vue
# npm 7+, 需要额外的双横线:
npm init vite@latest my-vue-app -- --template vue

1-5vue-router routing

https://router.vuejs.org/zh/

npm install vue-router@4

2. Global import (according to your own needs)

import {
    
     createApp } from "vue";
import "./style.css";
import App from "./App.vue";
import router from "./router";
import vant from "vant";
import "vant/lib/index.css";
import "./assets/fonts/iconfont.css";
import "virtual:windi.css";
// vant4 图片全局注册组件
import {
    
     Image as VanImage } from "vant";
//导入文件
import store from "./store/index";

const app = createApp(App);
//挂载router
app.use(router);
app.use(vant);
app.use(store);
app.mount("#app");
app.use(VanImage);

3. Use of json-server

The prerequisite for using json-server is to install node.js

//使用npm全局安装json-server:
npm install -g json-server
//可以通过查看版本号,来测试是否安装成功:
json-server -v

Create json data——
Since db.json is creating data, you need to create a json data.
Create a db.json in the same directory as src to store data
and execute code:

json-server --watch db.json

insert image description here
insert image description here

Acquisition of json data

http://localhost:3000/user
// 其中3000是端口号,json-server 默认是 3000 端口,我们也可以自己指定端口,指令如下:
json-server --watch db.json --port 3004
//user代表db数据里数据对象
 $.ajax({
    
    
    type: "get",
    url: "http://localhost:3000/user",
    success: function (data) {
    
    
      for (var i = 0; i < data.length; i++) {
    
    
        if (
          data[i].accounts == accounts.value &&
          data[i].password == password.value
        ) {
    
    
          //学生帐号
          if (data[i].key == 1) {
    
    
            showDialog({
    
    
              message: "账号密码正确,跳转到学生首页",
            }).then(() => {
    
    
              // on close
              store.commit("setUserId", data[i].id);
              localStorage.setItem("userId", data[i].id);
              router.push("/studentIndex");
            });
          }
          //老师帐号
          if (data[i].key == 2) {
    
    
            showDialog({
    
    
              message: "账号密码正确,跳转老师首页",
            }).then(() => {
    
    
              // on close
              store.commit("setUserId", data[i].id);
              localStorage.setItem("userId", data[i].id);
              router.push("/teacherIndex");
            });
          }
          return;
        } else {
    
    
          showDialog({
    
    
            message: "账号密码错误",
          }).then(() => {
    
    
            // on close
          });
        }
      }
    },
    error: function () {
    
    
      console.log("获取失败");
    },
  });

insert image description here
But there will be a problem, saying that your $ is not defined, I found a solution after reading many articles, importing at the logic layer

import $ from "jquery";
window.jQuery = $;
window.$ = $;

In this way, the problem can be solved perfectly.
After the problem is solved, the data can be added, deleted, modified and checked.

The increase of json data

As follows, use the post method to pass data into the user in db.json

$.ajax({
    
    
    type: "post",
    url: "http://localhost:3000/user",
    data: {
    
    
      accounts: accounts.value,
      password: password.value,
      userName: userName.value,
      identity: identity.value,
      teaNumber: teaNumber.value,
      sex: checked.value,
      phone: phone.value,
      department: identity.value,
      key: 2,
    },
    success: function (data) {
    
    
      showDialog({
    
    
        message: "注册成功,跳转到登录界面",
      }).then(() => {
    
    
        // on close
        router.push("/");
      });
    },
    error: function () {
    
    
      alert("post error");
    },
  });

Update of json data

type here uses the patch method, and there is also a put method for data update, but it is not recommended to use it here. The PUT method will update the entire resource object, and the fields not given by the front end will be automatically cleared.
The userId below is the id, we update the data according to the id

$.ajax({
    
    
    type: "patch",
    url: "http://localhost:3000/user/" + userId,
    data: {
    
    
      subject: subject.value,
    },
    success: function (data) {
    
    
      console.log("put success");
    },
    error: function () {
    
    
      alert("put error");
    },
  });

Deletion of json data

Similarly, here we also delete data based on id

     $.ajax({
    
    
        type: "delete",
        url: "http://localhost:3000/news/" + strToObj.id,
        success: function(data) {
    
    
          router.push("/notify");
        },
        error: function() {
    
    
          alert("del error");
        },
      });

4. The data is saved in the browser (vuex method)

First of all, we need to know what vuex is. Vuex is a state management tool specially developed for Vue.js applications. It uses centralized storage to manage the state of all components of the application, and the only way to change the state is to modify it in mutations State, actions cannot directly modify the state
1.state data storage
2.getter state calculation properties
3.mutation logic synchronous operation that changes the state in the state
4.action submit mutation asynchronous operation
5.model modularization

1. Configure vuex

You can also check the vuex option when creating a project with scaffolding. The system will automatically create it.
If you use scaffolding to create, you don’t need to do anything, and you can ignore this step.

npm install vuex@next --save

Create a new store file -> index.js, configure as follows, and import it in main.js

import Vue from 'vue'
import Vuex from 'vuex'
 
Vue.use(Vuex)
 
export default new Vuex.Store({
    
    
  //数据,相当于data
  state: {
    
    
    
  },
  getters: {
    
    
    
  },
  //里面定义方法,操作state方发
  mutations: {
    
    
    
  },
  // 操作异步操作mutation
  actions: {
    
    
    
  },
  modules: {
    
    
    
  },
})

insert image description here

2. state basic data, store variables

const store = new Vuex.Store({
    
    
state: {
    
    
    a: 'true',
    b: 2,
    c: false,
    d: null
  },
});

when using

this.$store.state.a

3.getter: data derived from the basic data (state), equivalent to the calculated property of the state, and a method with a return value

getter: {
    
    
    a: state => state.a,
    b: function(state){
    
    
      return state.b * 2
  	}
  }

when using

this.$store.getters.a

4.mutation: The method of submitting updated data must be synchronous

mutations: {
    
    
    a: (state, userId) => {
    
    
      state.userId = userId
    },
    b: (state, token) => {
    
    
      // console.log(token)
      state.token = token
    }
  },

5. Data Storage and Retrieval

store/index.js

// 导入vuex 创建实例方法
import {
    
     createStore } from "vuex";
// 创建实例对象
const store = createStore({
    
    
  state() {
    
    
    return {
    
    
      // 共用属性:用户信息
      userId: "",
      newsData: "",
      token: "",
    };
  },
  mutations: {
    
    
    // 共用方法: 设置用户信息
    setUserId(state, id) {
    
    
      state.userId = id;
    },
    setNewsData(state, data) {
    
    
      state.newsData = data;
    },
  },
});
// 导出数据对象
export default store;
 store.commit("setUserId", data[i].id);
 // setUserId 是 调用的mutation里的方法,对state里的公共属性进行给值,将data[i].id的值进行传递,
 
 localStorage.setItem("userId", data[i].id);
 //把data[i].id的值存到userId中
 const userId = localStorage.getItem("userId");
 //把userId的值拿出来

5. Axios request data

1. Secondary packaging axios

npm install axios
或者
cnpm install axios

2. Secondary packaging axios

In actual projects, we generally do not directly use the installed axios, but perform secondary packaging. Next, we will simply package. The first step is to
create utils/http.js
and create utils under the src file Folder, create http.js file in utils
The second part writes http.js

//引入安装好的axios插件
import axios from "axios";
// 查询数据
const get = (url, params) => {
    
    
    return axios.get(url);
};
// 添加数据
const post = (url, data) => {
    
    
    return axios.post(url, data);
};
// 修改数据
const put = (url, data) => {
    
    
    return axios.put(url, data);
};

// 删除数据
const del = (url, data) => {
    
    
    return axios.delete(url);
};

//将二次封装好的axios导出
export {
    
     get, post, put, del };

3. The project uses axios

1. vue/cli scaffolding configuration proxy - vue.config.js solves cross-domain problems

The port of the project is 8080, and the port of the json file is 3000, which will involve cross-domain, and there are many ways to solve cross-domain. Here is an explanation of configuring the proxy agent to create a file
vue.config.js in the root directory, covering Some content of webpack.

module.exports = {
    
    
  devServer: {
    
    
    proxy: {
    
    
      "/api": {
    
    
        // 此处的写法,目的是为了 将/api 替换成 http://localhost:3000
        target: "http://localhost:3000",
        //是否跨域
        changeOrigin: true,
        //路径重写 下面示例为 将 /api 替换成空
        pathRewrite: {
    
    
          "^/api": "",
        },
      },
    },
  },
};

2.vite configuration agent - -vite.config.js

import vue from '@vitejs/plugin-vue';
import {
    
     defineConfig } from 'vite';

// https://vitejs.dev/config/
export default defineConfig({
    
    
  plugins: [vue()],
  server: {
    
    
    proxy: {
    
    
      '/api': {
    
    
        target: 'http://localhost:3000',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  }
});

3. Send axios request

<script>
import {
    
     get, post, put, del } from "./utils/http";
export default {
    
    
  methods: {
    
    
    // get查询infomation的所有信息
    async sendRequest() {
    
    
      let res = await get("/api/infomation");
      console.log("get查询infomation的所有信息", res);
    },
    // get查询infomation的id为1信息
    async sendRequest2() {
    
    
      let res2 = await get("/api/infomation/1");
      console.log("get查询infomation的id为1信息", res2);
    },
    // post添加infomation数据
    async sendRequest3() {
    
    
      let res3 = await post("/api/infomation", {
    
    
        title: "json-server 的第xxx条数据",
        desc: "奥特曼不想打小怪",
        author: "被奥特曼打了",
      });
      console.log(res3, "post添加infomation数据成功");
    },
    // pust修改infomation的id为1信息
    async sendRequest4() {
    
    
      let res4 = await put("/api/infomation/1", {
    
    
        title: "json-server 的第x+1条数据",
        desc: "奥特曼想打小怪111",
        author: "2222被奥特曼打了",
      });
      console.log(res4, "pust修改infomation的id为1信息成功");
    },
    // del删除infomation的id为1信息
    async sendRequest5() {
    
    
      let res4 = await del("/api/infomation/1");
      console.log(res4, "del删除infomation的id为1信息数据成功");
    },
  },
};
</script>

Guess you like

Origin blog.csdn.net/z2000ky/article/details/128774892