Nuxt主要功能介绍

使用感想

最近有个项目需要用到SEO,不想使用jquery;做了一番思想斗争后决定使用nuxt来处理,上手非常简单,使用起来基本来Vue中的SPA项目一样;鉴于官方文档需要讲解的配置参数过多,可能会看起来很复杂,实际上只要了解下面几点就能正常开发了

什么是服务器端渲染 (SSR)?

Vue.js 是构建客户端应用程序的框架。默认情况下,可以在浏览器中输出 Vue 组件,进行生成 DOM 和操作 DOM。然而,也可以将同一个组件渲染为服务器端的 HTML 字符串,将它们直接发送到浏览器,最后将这些静态标记"激活"为客户端上完全可交互的应用程序。

为什么使用服务器端渲染 (SSR)?

  • 更好的 SEO,由于搜索引擎爬虫抓取工具可以直接查看完全渲染的页面。
  • 更快的内容到达时间 (time-to-content)

Nuxt.js 是什么?

Nuxt 是一个基于 Vue 生态的更高层的框架

Nuxt.js 框架是如何运作的?

Vue 2

Vue-Router

Vuex

Vue 服务器端渲染

Vue-Meta

主要特性

  • 基于 Vue.js

  • 自动代码分层

  • 服务端渲染

  • 强大的路由功能,支持异步数据

  • 静态文件服务

  • ES2015+ 语法支持

  • 打包和压缩 JS 和 CSS

  • HTML 头部标签管理

  • 本地开发支持热加载

  • 集成 ESLint

  • 支持各种样式预处理器: SASS、LESS、 Stylus 等等

  • 支持 HTTP/2 推送

流程图

在这里插入图片描述

视图

在这里插入图片描述

路由

[Nuxt.js 依据 pages 目录结构自动生成vue-router模块的路由配置。

布局

<template>
  <nuxt />
</template>

页面

<template>
  <h1 class="red">Hello {{ name }}!</h1>
</template>

<script>
  export default {
    asyncData (context) {
      // called every time before loading the component
      return { name: 'World' }
    },
    fetch () {
      // The fetch method is used to fill the store before rendering the page
    },
    head () {
      // Set Meta Tags for this Page
    },
    // and more functionality to discover
    ...
  }
</script>

<style>
  .red {
    color: red;
  }
</style>

异步数据

asyncData 的方法,使得我们可以在设置组件的数据之前能异步获取或处理数据。

使用方法

  • 返回一个 Promise

    export default {
      asyncData({ params }) {
        return axios.get(`https://my-api/posts/${params.id}`).then(res => {
          return { title: res.data.title }
        })
      }
    }
    
  • 使用 async 或 await

    export default {
      async asyncData({ params }) {
        const { data } = await axios.get(`https://my-api/posts/${params.id}`)
        return { title: data.title }
      }
    }
    
  • 使用回调函数

    export default {
      asyncData({ params }, callback) {
        axios.get(`https://my-api/posts/${params.id}`).then(res => {
          callback(null, { title: res.data.title })
        })
      }
    }
    

插件

首先增加文件 plugins/vue-notifications.js

import Vue from 'vue'
import VueNotifications from 'vue-notifications'

Vue.use(VueNotifications)

然后, 在 nuxt.config.js 内配置 plugins 如下:

module.exports = {
  plugins: ['~/plugins/vue-notifications']
}

模块(扩展)

模块是 Nuxt.js 扩展,可以扩展其核心功能并添加无限的集成。

  • 插件
  • 自定义loader
  • 扩展webpack配置
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值