vue3+ts+element plus 使echarts自适应(推荐)

本文介绍了如何在Vue3、TypeScript和Element Plus环境中利用ECharts的resize方法实现图表的自适应。关键在于找到合适的时机调用resize方法以确保ECharts在页面布局变化时能正确调整大小。

思路就是通过echarts官方的方法resize方法。不过vue3你需要一个时机去调用这个方法

<template>
  <el-row :gutter="10">
    <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>Card name</span>
            <el-button class="button" type="text">Operation button</el-button>
          </div>
        </template>
        <div style="height: 200px" ref="homeLaboratoryRef"></div>
      </el-card>
    </el-col>
    <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>Card name</span>
            <el-button class="button" type="text">Operation button</el-button>
          </div>
        </template>
        <div v-for="o in 4" :key="o" class="text item">
          {{ "List item " + o }}
        </div>
      </el-card>
    </el-col>
    <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>Card name</span>
            <el-button class="button" type="text">Operation button</el-button>
          </div>
        </template>
        <div v-for="o in 4" :key="o" class="text item">
          {{ "List item " + o }}
        </div>
      </el-card>
    </el-col>
    <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>Card name</span>
            <el-button class="button" type="text">Operation button</el-button>
          </div>
        </template>
        <div v-for="o in 4" :key="o" class="text item">
          {{ "List item " + o }}
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<script lang="ts">
import * as echarts from 'echarts'
import {
  toRefs,
  reactive,
  onMounted,
  nextTick,
  computed,
  getCurrentInstance,
  watch,
  onActivated
} from 'vue'

export default {
  setup () {
    const { proxy } = getCurrentInstance() as any
    const state = reactive({
      myCharts: []
    })
    const initHomeLaboratory = () => {
      const myChart = echarts.init(proxy.$refs.homeLaboratoryRef)
      const option = {
        grid: {
          top: 50,
          right: 20,
          bottom: 30,
          left: 30
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['预购队列', '最新成交价'],
          right: 13
        },
        color: [
          '#63caff',
          '#49beff',
          '#03387a',
          '#03387a',
          '#03387a',
          '#6c93ee',
          '#a9abff',
          '#f7a23f',
          '#27bae7',
          '#ff6d9d',
          '#cb79ff',
          '#f95b5a',
          '#ccaf27',
          '#38b99c',
          '#93d0ff',
          '#bd74e0',
          '#fd77da',
          '#dea700'
        ],
        xAxis: {
          data: [
            '1月',
            '2月',
            '3月',
            '4月',
            '5月',
            '6月',
            '7月',
            '8月',
            '9月',
            '10月',
            '11月',
            '12月'
          ]
        },
        yAxis: [
          {
            type: 'value',
            name: '价格'
          }
        ],
        series: [
          {
            name: '预购队列',
            type: 'bar',
            data: [200, 85, 112, 275, 305, 415, 441, 405, 275, 305, 415, 441],
            itemStyle: {
              barBorderRadius: [4, 4, 0, 0],
              color: {
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                type: 'linear',
                global: false,
                colorStops: [
                  {
                    offset: 0,
                    color: '#0b9eff'
                  },
                  {
                    offset: 1,
                    color: '#63caff'
                  }
                ]
              }
            }
          },
          {
            name: '最新成交价',
            type: 'line',
            data: [50, 85, 22, 155, 170, 25, 224, 245, 285, 300, 415, 641],
            itemStyle: {
              color: '#febb50'
            }
          }
        ]
      }
      myChart.setOption(option)
      state.myCharts.push(myChart)
    }
    // 批量设置 echarts resize
    const initEchartsResizeFun = () => {
      nextTick(() => {
        for (let i = 0; i < state.myCharts.length; i++) {
          state.myCharts[i].resize()
        }
      })
    }
    // 批量设置 echarts resize
    const initEchartsResize = () => {
      window.addEventListener('resize', initEchartsResizeFun)
    }
    // 页面加载时
    onMounted(() => {
      initHomeLaboratory()
      initEchartsResize()
    })
    // 由于页面缓存原因,keep-alive
    onActivated(() => {
      initEchartsResizeFun()
    })
    // 监听 vuex 中的 tagsview 开启全屏变化,重新 resize 图表,防止不出现/大小不变等
    // watch(
    //   () => store.state.tagsViewRoutes.isTagsViewCurrenFull,
    //   () => {
    //     initEchartsResizeFun()
    //   }
    // )
    return {
      ...toRefs(state)
    }
  }
}
</script>

<style lang="less" scoped></style>

<think>我们使用Vue3、TypeScript和Element Plus创建一个404页面。步骤如下: 1. 创建404组件:在`src/views`目录下创建`NotFound.vue`文件 2. 配置路由:在路由配置中将404页面设置为通配符路由 3. 使用Element Plus组件设计404页面 ### 步骤1:创建404组件 在`src/views`目录下创建`NotFound.vue`文件: ```vue <template> <div class="not-found-container"> <el-empty description="页面不存在" :image-size="400"> <template #image> <!-- 可以使用Element Plus自带的图片,也可以自定义 --> <img src="@/assets/404.png" alt="404" v-if="false" /> <!-- 这里只是示例,实际使用时可以替换 --> <div class="custom-image"> <svg-icon icon-class="404" class="custom-icon" /> <!-- 如果使用svg图标 --> </div> </template> <el-button type="primary" @click="goHome">返回首页</el-button> </el-empty> </div> </template> <script lang="ts"> import { defineComponent } from &#39;vue&#39;; import { useRouter } from &#39;vue-router&#39;; export default defineComponent({ name: &#39;NotFound&#39;, setup() { const router = useRouter(); const goHome = () => { router.push(&#39;/&#39;); }; return { goHome }; } }); </script> <style scoped> .not-found-container { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f5f7fa; } .custom-image { font-size: 120px; color: #909399; } </style> ``` ### 步骤2:配置路由 修改路由配置文件(通常位于`src/router/index.ts`): ```typescript import { createRouter, createWebHistory, RouteRecordRaw } from &#39;vue-router&#39;; import Home from &#39;../views/Home.vue&#39;; const routes: Array<RouteRecordRaw> = [ { path: &#39;/&#39;, name: &#39;Home&#39;, component: Home }, // ...其他路由 { path: &#39;/:pathMatch(.*)*&#39;, // 匹配所有未匹配的路由 name: &#39;NotFound&#39;, component: () => import(&#39;../views/NotFound.vue&#39;) } ]; const router = createRouter({ history: createWebHistory(), routes }); export default router; ``` ### 步骤3:设计404页面(使用Element Plus) 在上面的`NotFound.vue`中,我们使用了Element Plus的`el-empty`组件来展示404页面。你也可以自定义内容,比如: ```vue <template> <div class="not-found"> <div class="not-found-content"> <h1 class="error-code">404</h1> <p class="error-message">页面不存在</p> <el-button type="primary" @click="goHome">返回首页</el-button> </div> </div> </template> <script lang="ts"> import { defineComponent } from &#39;vue&#39;; import { useRouter } from &#39;vue-router&#39;; export default defineComponent({ setup() { const router = useRouter(); const goHome = () => { router.push(&#39;/&#39;); }; return { goHome }; } }); </script> <style scoped> .not-found { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f5f7fa; } .not-found-content { text-align: center; } .error-code { font-size: 120px; margin: 0; color: #409eff; } .error-message { font-size: 24px; margin: 20px 0; } </style> ``` ### 使用SVG图标(可选) 如果你想要使用SVG图标,可以安装`svg-sprite-loader`,然后创建一个`SvgIcon`组件。这里不再展开,但你可以参考以下步骤: 1. 安装依赖:`npm install svg-sprite-loader -D` 2. 创建`src/icons`目录,将svg文件放入其中 3. 创建`src/components/SvgIcon.vue`组件 4. 在`main.ts`中全局注册`SvgIcon`组件 5. 在`vue.config.js`中配置`svg-sprite-loader` ### 注意事项 - 确保路由配置中404路由放在最后,因为路由匹配是从上到下的 - 使用`<img>`标签时,注意图片路径(建议使用`@/assets`) ### 完整示例代码 404页面组件(使用自定义布局): ```vue <template> <div class="not-found"> <div class="content"> <h1>404</h1> <p>抱歉,您访问的页面不存在</p> <el-button type="primary" @click="goHome">返回首页</el-button> </div> </div> </template> <script lang="ts"> import { defineComponent } from &#39;vue&#39;; import { useRouter } from &#39;vue-router&#39;; export default defineComponent({ name: &#39;NotFound&#39;, setup() { const router = useRouter(); const goHome = () => { router.push(&#39;/&#39;); }; return { goHome }; } }); </script> <style scoped> .not-found { display: flex; justify-content: center; align-items: center; height: 100vh; background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); } .content { text-align: center; } h1 { font-size: 150px; margin: 0; color: #409eff; line-height: 1; } p { font-size: 24px; color: #606266; margin: 20px 0; } </style> ``` 路由配置(`src/router/index.ts`): ```typescript import { createRouter, createWebHistory, RouteRecordRaw } from &#39;vue-router&#39;; const routes: Array<RouteRecordRaw> = [ // ... 其他路由 // 404路由必须放在最后 { path: &#39;/:pathMatch(.*)*&#39;, name: &#39;NotFound&#39;, component: () => import(&#39;@/views/NotFound.vue&#39;) } ]; const router = createRouter({ history: createWebHistory(), routes }); export default router; ``` 这样,当用户访问不存在的路径时,就会显示404页面,并有一个按钮可以返回首页[^1][^2][^3]。 §§相关问题§§ 1. Vue3中如何配置路由守卫? 2. Element Plus的Empty组件有哪些属性可以自定义? 3. 在Vue3项目中如何全局注册组件? 4. 如何优化Vue3项目的路由懒加载?</think>在 Vue3 项目中结合 TypeScript 和 Element Plus 创建 404 页面,可以按照以下步骤实现: ### 一、创建 404 页面组件 1. 在 `src/views` 目录下创建 `NotFound.vue` 文件: ```vue <template> <div class="not-found-container"> <el-empty :image-size="400" description="页面不存在"> <template #image> <div class="error-code">404</div> </template> <p class="error-message">抱歉,您访问的页面不存在</p> <el-button type="primary" @click="goHome">返回首页</el-button> </el-empty> </div> </template> <script lang="ts"> import { defineComponent } from &#39;vue&#39;; import { useRouter } from &#39;vue-router&#39;; export default defineComponent({ name: &#39;NotFound&#39;, setup() { const router = useRouter(); const goHome = () => { router.push(&#39;/&#39;); }; return { goHome }; } }); </script> <style scoped> .not-found-container { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f5f7fa; } .error-code { font-size: 120px; font-weight: bold; color: #409eff; line-height: 1; } .error-message { margin: 20px 0; font-size: 18px; color: #606266; } </style> ``` ### 二、配置路由 1. 在 `src/router/index.ts` 中配置路由: ```typescript import { createRouter, createWebHistory, RouteRecordRaw } from &#39;vue-router&#39;; import Home from &#39;../views/Home.vue&#39;; import NotFound from &#39;../views/NotFound.vue&#39;; // 导入404组件 const routes: Array<RouteRecordRaw> = [ { path: &#39;/&#39;, name: &#39;Home&#39;, component: Home }, // ...其他路由配置 { // 匹配所有未定义的路由 path: &#39;/:pathMatch(.*)*&#39;, name: &#39;NotFound&#39;, component: NotFound } ]; const router = createRouter({ history: createWebHistory(), routes }); export default router; ``` ### 三、添加 Element Plus 支持(如果尚未安装) 1. 安装 Element Plus: ```bash npm install element-plus @element-plus/icons-vue ``` 2. 在 `src/main.ts` 中引入: ```typescript import { createApp } from &#39;vue&#39;; import ElementPlus from &#39;element-plus&#39;; import &#39;element-plus/dist/index.css&#39;; import App from &#39;./App.vue&#39;; import router from &#39;./router&#39;; const app = createApp(App); app.use(ElementPlus); app.use(router); app.mount(&#39;#app&#39;); ``` ### 四、使用说明 1. **页面效果**: - 显示大号 "404" 错误代码 - 使用 Element Plus 的 `el-empty` 组件展示空状态 - 包含返回首页按钮 - 自适应布局,居中显示 2. **路由匹配规则**: ```typescript path: &#39;/:pathMatch(.*)*&#39; // 匹配所有未定义的路由 ``` 3. **自定义选项**: - 修改 `error-code` 样式可调整 404 数字的样式 - 修改 `error-message` 可更改提示文本 - 在 `el-empty` 组件中添加自定义图标: ```vue <template #image> <el-icon :size="100"><Warning /></el-icon> <div class="error-code">404</div> </template> ``` ### 五、完整项目结构示例 ``` src/ ├── views/ │ ├── Home.vue │ ├── About.vue │ └── NotFound.vue # 404页面组件 ├── router/ │ └── index.ts # 路由配置 ├── App.vue └── main.ts # 主入口文件 ``` ### 六、测试验证 1. 启动开发服务器: ```bash npm run dev ``` 2. 访问不存在的路由,如 `http://localhost:3000/non-existent-page`,将显示 404 页面[^1][^2][^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值