search
HomeWeb Front-endFront-end Q&AHow to implement data interaction in Vue.js without using a database

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>{{item.name}}-{{item.age}}</li>
    </ul>
  </div>
</template>
<script>
import axios from &#39;axios&#39;
export default {
  data () {
    return {
      dataList:[],
    }
  },
  created () {
    axios.get(&#39;/data.json&#39;)
      .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>{{item.name}}-{{item.age}}</li>
    </ul>
  </div>
</template>
<script>
import axios from &#39;axios&#39;
export default {
  data () {
    return {
      dataList:[],
    }
  },
  created () {
    axios.get(&#39;/api/getData&#39;)
      .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>
    <button>添加</button>
    <ul>
      <li>{{item}}</li>
    </ul>
  </div>
</template>
<script>
export default {
  data () {
    return {
      inputVal: &#39;&#39;,
      dataList:[],
    }
  },
  methods: {
    add () {
      if (!this.inputVal) return
      this.dataList.push(this.inputVal)
      window.localStorage.setItem(&#39;dataList&#39;, JSON.stringify(this.dataList))
      this.inputVal = &#39;&#39;
    }
  },
  created () {
    let localData = window.localStorage.getItem(&#39;dataList&#39;)
    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
What is useEffect? How do you use it to perform side effects?What is useEffect? How do you use it to perform side effects?Mar 19, 2025 pm 03:58 PM

The article discusses useEffect in React, a hook for managing side effects like data fetching and DOM manipulation in functional components. It explains usage, common side effects, and cleanup to prevent issues like memory leaks.

Explain the concept of lazy loading.Explain the concept of lazy loading.Mar 13, 2025 pm 07:47 PM

Lazy loading delays loading of content until needed, improving web performance and user experience by reducing initial load times and server load.

How does currying work in JavaScript, and what are its benefits?How does currying work in JavaScript, and what are its benefits?Mar 18, 2025 pm 01:45 PM

The article discusses currying in JavaScript, a technique transforming multi-argument functions into single-argument function sequences. It explores currying's implementation, benefits like partial application, and practical uses, enhancing code read

What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code?What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code?Mar 18, 2025 pm 01:44 PM

Higher-order functions in JavaScript enhance code conciseness, reusability, modularity, and performance through abstraction, common patterns, and optimization techniques.

How does the React reconciliation algorithm work?How does the React reconciliation algorithm work?Mar 18, 2025 pm 01:58 PM

The article explains React's reconciliation algorithm, which efficiently updates the DOM by comparing Virtual DOM trees. It discusses performance benefits, optimization techniques, and impacts on user experience.Character count: 159

How do you connect React components to the Redux store using connect()?How do you connect React components to the Redux store using connect()?Mar 21, 2025 pm 06:23 PM

Article discusses connecting React components to Redux store using connect(), explaining mapStateToProps, mapDispatchToProps, and performance impacts.

What is useContext? How do you use it to share state between components?What is useContext? How do you use it to share state between components?Mar 19, 2025 pm 03:59 PM

The article explains useContext in React, which simplifies state management by avoiding prop drilling. It discusses benefits like centralized state and performance improvements through reduced re-renders.

How do you prevent default behavior in event handlers?How do you prevent default behavior in event handlers?Mar 19, 2025 pm 04:10 PM

Article discusses preventing default behavior in event handlers using preventDefault() method, its benefits like enhanced user experience, and potential issues like accessibility concerns.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function