拆分axios 安装 json-server

拆分axios 安装 json-server,第1张

https://blog.csdn.net/lzfengquan/article/details/119413300?spm=1001.2101.3001.6661.1&utm_medium=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1-119413300-blog-124178042.pc_relevant_default&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1-119413300-blog-124178042.pc_relevant_default&utm_relevant_index=1\

安装 json-server

npm install -g json-server

json-server -v

json-server --watch data/db.json

{
    "posts":[
      {
        "title":"zt.js",
        "body":"db本课程",
        "id":1,
        "tags":[
            "vue3",
            "compositionApi",
            "blog"
        ]
      },
      {
        "title":"zt.js",
        "body":"db本课程",
        "id":2,
        "tags":[
            "vue3",
            "compositionApi",
            "blog"
        ]
      },
      {
        "title":"zt.js",
        "body":"db本课程",
        "id":3,
        "tags":[
            "vue3",
            "compositionApi",
            "blog"
        ]
      }

    ]
}

import { ref } from "vue";
import axios from 'axios'

const getPosts=()=>{

    const posts = ref([]);

    
    const load=async()=>{
    try{
        let { data } =await axios("http://localhost:3000/posts")
        posts.value=data
    
    }catch(error){
      console.log(error)
    }
  

}

return {posts,load}
}

export default getPosts


  




安装 axios    安装router

npm install vue-router

 npm i axios

  定义router /   router.js

import { createRouter,createWebHistory } from "vue-router";
import Home from '../views/Home.vue'
import Details from '../views/Details.vue'
const routes=[
    {path:"/",name:'Home',component:Home},
    {path:"/posts/:id",name:'Details',component:Details,props:true}
]
const router =createRouter(
    {
        history:createWebHistory(),
        routes
    }
)

export default router

获取详情 接口数据模拟

import { ref } from "vue";
import axios from 'axios'

const getPost=(id)=>{

    const post = ref({});

    
    const load=async()=>{
    try{
        let { data } =await axios("http://localhost:3000/posts/"+id)
        post.value=data
    
    }catch(error){
      console.log(error)
    }
  

}

return {post,load}
}

export default getPost

配置 点击进去详情页 

  SinglePost.vue

    
         {{post.title}}
         


router/index.js

{path:"/posts/:id",name:'Details',component:Details,props:true}

views/Detail.vue





欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1297905.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-10
下一篇 2022-06-10

发表评论

登录后才能评论

评论列表(0条)

保存