Home >Web Front-end >Front-end Q&A >How to implement data interaction in Vue.js without using a database

How to implement data interaction in Vue.js without using a database

PHPz
PHPzOriginal
2023-04-13 10:46:09959browse

With the advancement of Internet technology and the increasing number of application scenarios, front-end technology is also developing day by day. In recent years, front-end frameworks have become one of the indispensable weapons for developers. One of the popular open source JavaScript frameworks is Vue.js, a progressive framework for building web user interfaces. It enables rapid development through lightweight data binding, componentized architecture, and rich APIs.

However, vue uses ajax requests and back-end databases for data interaction. This method is very common during development. However, some small projects do not need to use a database for data interaction. For example, they only need to obtain local data, and then there is no need to use a database. So, how to implement data interaction in Vue.js without using a database?

1. Use json data

json data is a lightweight data exchange format. Its syntax rules are very simple and the data structure is clear. It is suitable for types that do not require the use of complex relational databases. small projects. It is very simple to use json data for data interaction in vue. We can put the json file in the public folder of the project, and then make data requests through axios or fetch.

// 在 public 文件夹下新建一个 data.json 文件
{
  "data": [
    {
      "name": "小明",
      "age": 18
    },
    {
      "name": "小红",
      "age": 20
    }
  ]
}
<!-- 在 Vue 组件中使用 axios 获取 json 数据 -->
<template>
  <div>
    <ul>
      <li v-for="(item,index) in dataList" :key="index">{{item.name}}-{{item.age}}</li>
    </ul>
  </div>
</template>
<script>
import axios from 'axios'
export default {
  data () {
    return {
      dataList:[],
    }
  },
  created () {
    axios.get('/data.json')
      .then(res => {
        console.log(res.data)
        this.dataList = res.data.data
      })
      .catch(err => {
        console.log(err)
      })
  },
}
</script>
2. Use mock data

Mock data refers to simulated data, which is the data we construct ourselves, used to simulate real data. It can be used to help front-end developers develop without back-end interfaces. Due to the small amount of data, mock data is generally placed locally in the front-end project (usually placed in the src/mock directory). Integrating mock.js in Vue is also relatively simple. We can introduce mock.js in main.js and then use express to simulate the backend interface.

// 安装 express 和 mockjs
npm i express mockjs -D

// 在 src/mock/index.js 中定义接口返回的数据
import Mock from 'mockjs'
let data = Mock.mock({
  "data|10-20": [
    {
      "id|+1": 1,
      "name": '@cname',
      "age|18-25": 18,
      "city": '@city',
      "address": '@county(true)',
      "img": "@image(50x50,@color)"
    }
  ]
})
Mock.mock('/api/getData', 'get', () => {
  return data
})

// 在 main.js 中引入 express 并注册中间件
import express from 'express'
const app = express()
const port = 3000
let apiRoutes = express.Router()
import './mock'
app.use('/api', apiRoutes)
app.listen(port, () => {
  console.log(`server running @${port}`)
})

// 在具体的组件中通过 axios 请求数据
<template>
  <div>
    <ul>
      <li v-for="(item,index) in dataList" :key="index">{{item.name}}-{{item.age}}</li>
    </ul>
  </div>
</template>
<script>
import axios from 'axios'
export default {
  data () {
    return {
      dataList:[],
    }
  },
  created () {
    axios.get('/api/getData')
      .then(res => {
        console.log(res.data)
        this.dataList = res.data.data
      })
      .catch(err => {
        console.log(err)
      })
  },
}
</script>
3. Use local storage

localStorage is a method of web storage mechanism. It can store some simple key-value data on the client. Its data is in the form of a string. are stored in the form of , so serialization and deserialization are required when storing objects and arrays. It is also very simple to use localStorage to store data in Vue. We can synchronize the data to localStorage while adding, deleting, modifying and checking the data, so that the previously stored data can be obtained from localStorage the next time the page is opened.

<template>
  <div>
    <input type="text" v-model="inputVal">
    <button @click="add">添加</button>
    <ul>
      <li v-for="(item,index) in dataList" :key="index">{{item}}</li>
    </ul>
  </div>
</template>
<script>
export default {
  data () {
    return {
      inputVal: '',
      dataList:[],
    }
  },
  methods: {
    add () {
      if (!this.inputVal) return
      this.dataList.push(this.inputVal)
      window.localStorage.setItem('dataList', JSON.stringify(this.dataList))
      this.inputVal = ''
    }
  },
  created () {
    let localData = window.localStorage.getItem('dataList')
    console.log(localData)
    if (localData !== null) {
      this.dataList = JSON.parse(localData)
    }
  },
}
</script>

In summary, for small projects, using json data, mock data and local storage are all good choices. Of course, for large applications, using a back-end database for data interaction is still the preferred solution. This article mainly introduces how to implement data interaction without using a database in Vue.js, which has certain reference value for beginners in Vue development.

The above is the detailed content of How to implement data interaction in Vue.js without using a database. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn