今天看了看Nuxt的官方文档。 我比较关心路由,asyncData(异步数据)
路由: 基础路由,动态路由,嵌套路由,动态嵌套路由 nuxt.js会依据pages项目结构自动生成路由, [``](/api/components-nuxt-link):自定义路由
基础路由: router: { routers: [ {name: ‘index’,path: ‘/’,component:‘pages/index.vue’}, {name: ‘user’,path: ‘/user’,component:‘pages/user/index.vue’}, {name: ‘user-one’,path: ‘/user/one’,component:‘pages/user/one.vue’}, ] }
动态路由 在nuxt.js里面定义带参数的动态路由,需要创建对应的以下划线为前缀的vue generate会忽略动态路由:API Configuration generate
嵌套路由 通过vue-router的子路由创建nuxt.js应用的嵌套路由 创建内嵌子路由,你需要添加一个vue文件,同时添加一个与改文件同名的目录用来存放子视图组件 别忘了在父组件(.vue文件)内增加<nuxt-child>用于显示子时图内容 router: { routes: [ { path: ‘/users’, component:‘pages/users.vue’, children:[ { path: ‘’, component: ‘pages/users/index.vue’, name=‘users’ }, { path: ‘:id’, component: ‘pages/users/_id.vue’, name=‘users-id’ }, ] } ] }
一个路由下边有子路由,子路由还有子路由,路由-》自路由-》孙路由, 动态嵌套路由 router: { routes: [ { path:’/’, component:‘pages/index.vue’, name: ‘index’ }, { path:’/:category’, component:‘pages/_category.vue’, children: [ { path:’’, component:‘pages/_category/index.vue’, name:‘category’ }, { path:’"subCategory’, component:‘pages/_category/_subCategory.vue’, children: [ { path:’’, component:‘pages/_category/_subCategory.vue’, name: ‘category-subCategory’ }, { path:’:id’, component: ‘pages/_category/_subCategory/_id.vue’, name:‘category-subCategory-id’ } ] } ] } ] }
中间件, 中间件定义函数,在页面渲染之前执行, 中间件放置在middleware里边,文件名名称将成为中间件名称。 一个中间件接受content作为第一个参数: exort default function(content){ content.userAgent = context.isServer ? context.req.header[‘user-agent’] :navigator.userAgent }
中间件可以一步执行,只需要返回一个Promise或使用第2个callback作为第一个参数 middleware/stats.js import axios form ‘axios’ export default function({route}){ return axios.post(‘http://my-stats-api.com’,{ url:route.fallPath }) } 然后在你的nuxt.config.js、layous或者pages中使用中间件: nuxt:config.js module.exports = { router: { middleware: ‘stats’ } } stats中间件将在每个路由改变时被调用
asyncData:异步数据 设置组件的数据之前能异步获取或处理数据 可以在服务端或路由跟新之前被调用。在这个方法被调用的时候,第一个参数被指定为当前页面的上下文对象,你可以利用asyncData来获取数据,Nuxt会将asyncData返回的 数据融合组件data方法返回的数据一并返回给当前组件。 asyncData是在初始化前被调用,注意this
nuxt.js提供了几种不同的方法来使用async方法: 1.返回一个Promise,nuxt.js会等待Promise被解析之后才会设置组件的数据,渲染 2.使用asyncData或await 3.为第二个参数指定一个回调函数,注:该回调函数需符合通用的node.js回调函数的形式:callback(err,data) axios可以在服务端和客户端使用
返回Promise export default { asyncData({params}){ return axios.get(‘http://my-api/posts/${params.id}’) .then((res)=> { return {title:res.data.title} }) } }
使用async或await export default{ async asyncData({}){ let {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}) }) } }
