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!

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

HTML5aimstoenhancewebcapabilities,makingitmoredynamic,interactive,andaccessible.1)Itsupportsmultimediaelementslikeand,eliminatingtheneedforplugins.2)Semanticelementsimproveaccessibilityandcodereadability.3)Featureslikeenablepowerful,responsivewebappl

HTML5aimstoenhancewebdevelopmentanduserexperiencethroughsemanticstructure,multimediaintegration,andperformanceimprovements.1)Semanticelementslike,,,andimprovereadabilityandaccessibility.2)andtagsallowseamlessmultimediaembeddingwithoutplugins.3)Featur

HTML5isnotinherentlyinsecure,butitsfeaturescanleadtosecurityrisksifmisusedorimproperlyimplemented.1)Usethesandboxattributeiniframestocontrolembeddedcontentandpreventvulnerabilitieslikeclickjacking.2)AvoidstoringsensitivedatainWebStorageduetoitsaccess

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

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