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 '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>{{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> <button>添加</button> <ul> <li>{{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!

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.

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

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

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

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

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

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.

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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
Useful JavaScript development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function