Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does the combined API of Vue 3 request data

2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "Vue 3 combination API how to request data", the article explains the content is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in depth, together to study and learn "Vue 3 combination API how to request data" bar!

Project initialization

To quickly launch a Vue 3 project, we initialize the project directly using Vite, the most popular tool of the day. The whole process was accomplished in one fell swoop.

Npm init vite-app vue3-app# opens the generated project folder cd vue3-app# installation depends on npm install # to start the project npm run dev

Let's open App.vue and delete the generated code first.

The entrance to the combined API

Next, we will get some hot articles through Hacker News API. The data structure returned by Hacker News API is as follows:

{"hits": [{"objectID": "24518295", "title": "Vue.js 3", "url": "https://github.com/vuejs/vue-next/releases/tag/v3.0.0",}, {...}, {...},]}

We display the news list on the interface through ui > li, and the news data is obtained from the hits traversal.

{{item.title}} import {reactive} from 'vue' export default {setup () {const state = reactive ({hits: []}) return state}}

Before explaining the data request, I think first take a look at the setup () method. The combination of API needs to be started through the setup () method. The data returned by setup () can be used in the template and can be simply understood as the data returned by the data () method in Vue 2. The difference is that the returned data needs to be wrapped through the reactive () method to turn the data into a response.

Request data in combined API

In Vue 2, when we request data, we usually need to put the code that initiated the request into a certain life cycle (created or mounted). Within the setup () method, we can use the lifecycle hook provided by Vue 3 to place the request within a specific lifecycle. The comparison of the lifecycle hook method with the previous lifecycle is as follows:

Life cycle

As you can see, basically an on is added to the previous method name, and no hook for onCreated is provided, because execution within setup () is equivalent to execution in the created phase. Let's request data in the mounted phase:

Import {reactive, onMounted} from 'vue' export default {setup () {const state = reactive ({hits: []}) onMounted (async () = > {const data = await fetch (' https://hn.algolia.com/api/v1/search?query=vue') .then (rsp = > rsp.json () state.hits = data.hits}) return state}}

The final effect is as follows:

Monitor data changes

Hacker News's query interface has a query parameter, which we fixed in the previous case, and now we define this variable through responsive data.

{{item.title}} import {reactive, onMounted} from 'vue' export default {setup () {const state = reactive ({query:' vue' Hits: []}) onMounted ((async ()) = > {const data = await fetch (`https://hn.algolia.com/api/v1/search?query=${state.query}`) .then (rsp = > rsp.json () state.hits = data.hits}) return state}}

Now that we modify the input box, we can trigger the state.query synchronous update, but not the fetch re-call, so we need to listen for changes in the response data through watchEffect ().

Import {reactive, onMounted, watchEffect} from 'vue' export default {setup () {const state = reactive ({query:' vue' Hits: []}) const fetchData = async (query) = > {const data = await fetch (`rsp.json) .then (rsp = > rsp.json ()) state.hits = data.hits} onMounted (() = > {fetchData (state.query) watchEffect () = > {fetchData (state). Query)})}) return state}}

Because when watchEffect () is called for the first time, its callback will be executed once, causing the interface to be requested twice during initialization, so we need to delete the fetchData in onMounted.

OnMounted (() = > {- fetchData (state.query) watchEffect (() = > {fetchData (state.query)})}))

WatchEffect () listens for all the responsive data in the incoming function, and once one of the data changes, the function reexecutes. If you want to unlisten, you can call the return value of watchEffect (), which is a function. Here's an example:

Const stop = watchEffect (() = > {if (state.query = 'vue3') {/ / stop listening to stop ()} fetchData (state.query)} when query is vue3)

When we type "vue3" in the input box, the request will not be made again.

Returns the event method

Now there is a problem is that each change in the value in input will trigger a request, we can add a button, click the button and then trigger the update of state.query.

Search for {{item.title}} import {reactive, onMounted, watchEffect} from 'vue' export default {setup () {const state = reactive ({input:' vue', query: 'vue' Hits: []}) const fetchData = async (query) = > {const data = await fetch (`rsp.json) .then (rsp = > rsp.json ()) state.hits = data.hits} onMounted (() = > {watchEffect (() = > {fetchData (state.query)})) }) const setQuery = () = > {state.query = state.input} return {setQuery State}

You can notice that the method of the click event bound by button is also returned by the setup () method, and we can understand the return value of the setup () method as the merge of the data () method and the methods object in Vue2.

The original return value state has become an attribute of the current return value, so when we fetch data in the template layer, we need to make some changes by adding state.

Search for {{item.title}}

Return data modification

As patients with obsessive-compulsive disorder, it is really difficult to obtain data through state.xxx at the template layer, so can we return the state data through object deconstruction?

Search for {{item.title}} import {reactive, onMounted, watchEffect} from 'vue' export default {setup (props, ctx) {const state = reactive ({input:' vue', query: 'vue', hits: []}) / / omit some code. Return {... state, setQuery,}

The answer is "no". After modifying the code, you can see that although the page initiates the request, the page does not display the data.

After the state is deconstructed, the data becomes static and can no longer be tracked, and the return value is similar to:

Export default {setup (props, ctx) {/ / omit some code. Return {input: 'vue', query:' vue', hits: [], setQuery,}

In order to track basic types of data (that is, non-object data), Vue3 also proposes a solution: ref ().

Import {ref} from 'vue' const count = ref (0) console.log (count.value) / / 0 count.value++ console.log (count.value) / / 1

The above is the official case of Vue 3. The ref () method returns an object. Whether it is modified or obtained, it needs to take the value property of the returned object.

We change the state from a response object to a normal object, and then all properties are wrapped in ref, so that the subsequent deconstruction will not take effect until it is modified. The drawback is that each property of state must take its value property when it is modified. However, there is no need to append .value to the template, which is processed internally in Vue 3.

Import {ref, onMounted, watchEffect} from 'vue' export default {setup () {const state = {input: ref (' vue'), query: ref ('vue') Hits: ref ([])} const fetchData = async (query) = > {const data = await fetch (`https://hn.algolia.com/api/v1/search?query=${query}`) .then (rsp = > rsp.json ()) state.hits.value = data.hits} onMounted (() = > {watchEffect (() = > {fetchData (state.query.value)) })}) const setQuery = () = > {state.query.value = state.input.value} return {... state SetQuery,}

Is there a way to keep state as a response object while supporting its object deconstruction? Of course there is, and Vue 3 also provides a solution: toRefs (). The toRefs () method turns a response object into a normal object and adds ref () to each property.

Import {toRefs, reactive, onMounted, watchEffect} from 'vue' export default {setup () {const state = reactive ({input:' vue', query: 'vue' Hits: []}) const fetchData = async (query) = > {const data = await fetch (`rsp.json) .then (rsp = > rsp.json ()) state.hits = data.hits} onMounted (() = > {watchEffect (() = > {fetchData (state.query)})) }) const setQuery = () = > {state.query = state.input} return {... toRefs (state) SetQuery,}

Loading and Error statu

Usually, when we initiate a request, we need to add Loading and Error states to the request, and we only need to add two variables in the state to control these two states.

Export default {setup () {const state = reactive ({input: 'vue', query:' vue', hits: [], error: false, loading: false }) const fetchData = async (query) = > {state.error = false state.loading = true try {const data = await fetch (`https://hn.algolia.com/api/v1/search?query=${query}`) .then (rsp = > rsp.json () state.hits = data.hits} catch {state.error = true} State.loading = false} onMounted (() = > {watchEffect (()) = > {fetchData (state.query)})}) const setQuery = () = > {state.query = state.input} return {... toRefs (state) SetQuery,}

Use both variables in the template at the same time:

Search for Loading... Something went wrong... {{item.title}}

Display Loading and Error status:

Abstract data request logic

Students who have used umi must know that umi provides a Hooks called useRequest, which is very convenient to request data, so we can also abstract a public method similar to useRequest through the combination of Vue API.

Next, let's create a new file useRequest.js:

Import {toRefs, reactive,} from 'vue' export default (options) = > {const {url} = options const state = reactive ({data: {}, error: false, loading: false }) const run = async () = > {state.error = false state.loading = true try {const result = await fetch (url) .then (res = > res.json ()) state.data = result} catch (e) {state.error = true} state.loading = false} return {run,... toRefs (state)}}

Then introduce into App.vue:

Search for Loading... Something went wrong. {{item.title}} import {ref, onMounted} from 'vue' import useRequest from'. / useRequest' export default {setup () {const query = ref ('vue') const {data, loading, error Run} = useRequest ({url: 'https://hn.algolia.com/api/v1/search'}) onMounted (() = > {run ()}) return {data, query, error, loading, search: run,}

The current useRequest has two drawbacks:

The incoming url is fixed and cannot be reflected on the url in time after the query is modified.

Cannot request automatically. You need to call the run method manually.

Import {isRef, toRefs, reactive, onMounted,} from 'vue' export default (options) = > {const {url, manual = false, params = {}} = options const state = reactive ({data: {}, error: false, loading: false }) const run = async () = > {/ / stitching query parameter let query =''Object.keys (params) .forEach (key = > {const val = params [key] / / if you go to the ref object Need to take the .value attribute const value = isRef (val)? Val.value: val query + = `${key} = ${value} &`}) state.error = false state.loading = true try {const result = await fetch (`${url}? ${query}`) .then (res = > res.json () state.data = result} catch (e) {state.error = true} state.loading = false} onMounted (()) = > {/ / whether to call manually for the first time! manual & & run ()}) return {run ... toRefs (state)}}

After modification, our logic becomes extremely simple.

Import useRequest from'. / useRequest' export default {setup () {const query = ref ('vue') const {data, loading, error, run} = useRequest ({url:' https://hn.algolia.com/api/v1/search', params: {query}}) return {data, query, error, loading Search: run,} Thank you for reading The above is the content of "the combination of Vue 3 API how to request data". After the study of this article, I believe you have a deeper understanding of how the combination of Vue 3 API requests data, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report