Vue二次封装element-ui的树组件(一)

1.创建文件夹

2.

1)npm init -y  

2)安装 npm i express axios element-ui loadsh -S

3.创建server.js文件:写接口

let express = require('express')
let app = express();


//解决跨域问题
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*'); //允许任何语言跨域
  if (req.method === 'OPTIONS') {
    return res.send();
  }
  next();
})

app.get('/getTreeList', (req, res) => {
  res.json({
    code: 0,
    parent: [{
        name: '文件夹',
        pid: 0,
        id: 1
      },
      {
        name: '文件夹2',
        pid: 0,
        id: 2
      },
      {
        name: '文件夹3',
        pid: 0,
        id: 3
      },
      {
        name: '文件夹1-1',
        pid: 1,
        id: 4
      },
      {
        name: '文件夹2-1',
        pid: 2,
        id: 5
      }
    ],
    child: [{
        name: '文件1',
        pid: 1,
        id: 10001
      },
      {
        name: '文件2',
        pid: 1,
        id: 10002
      },
      {
        name: '文件2-1',
        pid: 2,
        id: 10003
      },
      {
        name: '文件2-2',
        pid: 2,
        id: 10004
      },
      {
        name: '文件1-1-1',
        pid: 4,
        id: 10005
      },
      {
        name: '文件2-1-1',
        pid: 5,
        id: 10006
      }
    ]
  })
})
app.listen(3040); //node server.js

run code 运行代码,访问lcalhost:304/getTreeList 路径可以看到自己写json数据

4.新建main.js文件,以及App.vue文件,api.js文件(用于二次封装axios)

main.js

import Vue from 'vue';
import App from './App.vue'
import ElementUI from 'element-ui'; //引入
import 'element-ui/lib/theme-chalk/index.css'; //引入样式
Vue.use(ElementUI); //注册使用

export default new Vue({
  el: '#app',
  render: h => h(App)
})

api.js

import axios from 'axios'

axios.defaults.baseURL = 'http://localhost:3040'

export const getTreeList = () => {
  return axios.get('/getTreeList')
}

  App.vue

<template>
  <div>

  </div>
</template>
<script>
import { getTreeList } from './api'
export default {
  async mounted () {
    let { data } = await getTreeList();
    console.log(data);
  }

}
</script>

使用 vue serve访问:

访问上面的链接可以看到控制台打印数据:

总文件目录:

发布了98 篇原创文章 · 获赞 4 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_42416812/article/details/101016806