一、获取本地json文件方式渲染
准备:在 static目录下存放一个json文件
<template>
<view class="func">
<!-- 这里的funcBlock是我自己写的组件,item为自定义的传数据,不必过于关注 -->
<funcBlock v-for="item in functext" :key="item.id" :item="item"></funcBlock>
</view>
</template>
<script setup>
// 引入本地json
import fixedData from '@/static/data/test.json'
// 将json中数组给functext(根据自己json文件的层级结构来使用)
const functext = fixedData.data
</script>
二、调用后端接口方式渲染
uniapp调用接口:
<template>
<view class="func">
<view v-for="item in func" :key="item.id">
<p>{{item.name}}</p>
</view>
</view>
</template>
<script setup>
import {ref} from 'vue'
//该请求方法可以根据自己需要进行封装,我这里采用原生静态写法
const request =uni.request({
url:`http://111.1.1.1/api/mon`, //请求地址
data: {month: '5'}, //发送到服务器的数据
method:'Get', //get、post
header: { 'content-type': 'application/json'}, //请求头的信息
success:res=>{}, //请求成功回调,带参数
fail:err=>{}, //请求失败
})
let func=ref([]) //定义一个数组来转存接收的数据
const data= async () => {
const res = await request();//调用request
console.log(res);//可在控制台查看自己获取的数据
//值得注意的是由于ref原理上是使用proxy代理,所以在赋值时需要.value
func.value=res.data//将返回的数据赋值给定义好的数组(这里根据自己获得的数据来赋值)
}
data()
</script>
使用axios方式调用接口:(vue3)
①利用webpack安装axios
npm install axios
②在main.js文件中引入
import axios from "axios"
③axios使用
<template>
<div class="func">
<div v-for="item in func" :key="item.id">
<p>{{item.}}</p>
</div>
</div>
</template>
<script setup>
import {ref} from 'vue'
//该请求方法可以根据自己需要进行封装,我这里采用原生静态写法
const request =axios.post('/user', {month: '5'})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
let func=ref([]) //定义一个数组来转存接收的数据
const data= async () => {
const res = await request();//调用request
console.log(res);//可在控制台查看自己获取的数据
//值得注意的是由于ref原理上是使用proxy代理,所以在赋值时需要.value
func.value=res.data//将返回的数据赋值给定义好的数组(这里根据自己获得的数据来赋值)
}
data()
</script>