【问题标题】:How to update head title after axios call in vue jsvue js中axios调用后如何更新头部标题
【发布时间】:2021-08-31 11:19:01
【问题描述】:

我有一个产品页面,我在其中传递产品 ID 并基于此我调用 rest Api 并且在 Api 响应之后我需要使用产品名称更新标题标签。我能够更新标题标签,但在查看源代码中我将值作为未定义或默认值。那么如何在开始时更新标题,以便在查看源中获取产品名称。所以这将是 SEO 友好的。

export default {
  name: 'App',
  components: {
    HelloWorld
  },
  data () {
    return {
      setTitle: {}
    }
  },
  created () {
    axios.get('https://apiurl.com/testing.json')
          .then((response) => {
            this.setTitle = response.data            
          })
  },
  metaInfo() {
    return {
      title: `${this.setTitle.product_name} product name`,
      meta: [
        {
          vmid: "description",
          name: "description",
          content:
            "hello world, this is an example of adding a description with vueMeta"
        }
      ]
    }
  }
}

如果在我的项目中 SSR 为假,是否有可能?

【问题讨论】:

    标签: javascript vue.js axios nuxt.js


    【解决方案1】:

    您应该使用 nuxt 提供的 asyncData 钩子,该钩子在创建页面之前运行(您不需要在 data 选项中定义 setTitle )并将 metaInfo 替换为 head

    export default{
     name: 'App',
      components: {
        HelloWorld
      },
     async asyncData() {
        const {data} = await  axios.get('https://apiurl.com/testing.json')
        return { setTitle:data} // without defining data option
      },
      head() {
        return {
          title: `${this.setTitle.product_name} product name`,
          meta: [
            {
              vmid: "description",
              name: "description",
              content:
                "hello world, this is an example of adding a description with vueMeta"
            }
          ]
        }
      }
    }
    

    【讨论】:

    • 它工作正常,但我想知道另一件事,我的 axios 代码采用另一种方法。所以我只想从 asyncData 函数中调用这个方法。我该怎么做。你能帮我解决这个问题吗?想在另一个方法中使用下面的axios调用&只需要从asyncData调用函数const {data} = await axios.get('https://apiurl.com/testing.json')
    • 因为我已经检查了我的项目 SSR 是假的,所以它不会更新 Api 响应上的标题标签。我不能像影响整个项目那样改变 SSR。你知道 SSR false 我们如何更新标题标签吗?有可能吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 2021-07-04
    • 2018-11-03
    相关资源
    最近更新 更多