NUXT 项目实战

nuxt 路由

路由容器<nuxt/>组件 相当于 vue的 <router-view></router-view>

<div class="container">
  <header class="header">this is header</header>
  <div class="con">
    <nuxt/>
  </div>
  <footer class="footer">this is footer</footer>
</div>

子路由<nuxt-child/>组件 注意 : 子路由需要在pages/文件夹下面放对应的路由容器<nuxt-child></nuxt-child>
/pages/home.vue

<div class="child">
  <nuxt-child></nuxt-child>
</div>

/pages/home/index.vue

路由跳转 <nuxt-link/> 别名: <n-link>, <NuxtLink>, 和 <NLink>

<template>
  <div class="about">
    <nuxt-link to="/about">关于</nuxt-link>
  </div>
</template>

客户端渲染组件<client-only/> 此组件用于仅在客户端渲染其他组件.

<template>
  <div>
    <sidebar />
    <client-only placeholder="Loading...">
      <!-- comments 组件只会在客户端被渲染 -->
      <comments />
    </client-only>
  </div>
</template>

异步数据 asyncData

注意:由于asyncData方法是在组件 初始化 前被调用的,所以在方法内是没有办法通过 this 来引用组件的实例对象。

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 }
  }
}

nuxt 插件

首先增加文件 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', ssr: true]
}

最后 插件里面要是否支持服务器端渲染,如果不支持。会报错
具体解决办法有。在试图里面添加

<client-only placeholder="Loading...">...dom</client-only>

或者在plugins/对应的插件里面 加上 ssr: false 即可解决

插件注入

  • 注入 Vue 实例
import Vue from 'vue'
Vue.prototype.$myInjectedFunction = string =>{
  console.log('This is an example', string)
}
  • 注入 context
export default ({ app }, inject) => {
  app.myInjectedFunction = string =>
    console.log('Okay, another function', string)
}

同时注入 vue 和 nuxt

如果您需要同时在context,Vue实例,甚至Vuex中同时注入,您可以使用inject方法,它是 plugin 导出函数的第二个参数。将内容注入 Vue 实例的方式与在 Vue 应用程序中进行注入类似。系统会自动将$添加到方法名的前面。

export default ({ app }, inject) => {
  inject('myInjectedFunction', string => console.log('That was easy!', string))
}

插件配置

module.exports = {
  plugins: [{ src: '~/plugins/vue-notifications', ssr: false }]
}
posted @ 2021-06-23 15:20  boygdm  阅读(249)  评论(0编辑  收藏  举报