我正试图在我的浏览器url中显示{{product.title}},请问我该怎么做

这是我的json对象

{
    "status": true,
    "product": {
        "_id": "625672a8370e769a8a93a51e",
        "title": "galaxy note",
        "description": "Lorem ",
    }
}

这是我的脚本标签


<script>

import axios from "axios";
export default {
  data() {
    return {
      product: []
    };
  },
  mounted() {
    axios
      .get(`http://localhost:5000/api/products/${this.$route.params.id}`, {})
      .then(response => {
        console.log(response);
        this.product = response.data.product;
      })
      .catch(error => {
        error;
      });
    axios
      .get(`http://localhost:5000/api/products`, {})
      .then(response => {
        console.log(response);
        this.product = response.data.product;
      })
      .catch(error => {
        error;
      });
  },
};
</script>

这是我的路由

  {path: "/products/:id", name: "Product", component: Product},

这是我go id路由的方式

 <router-link :to="`/products/${product._id}`">
          <img
            :src="product.photo"
            alt="Placeholder image"
          >
        </router-link>

默认情况下,它会显示http://localhost:8080/products/625672a8370e769a8a93a51e在我的url中,如何显示http://localhost:8080/products/galaxy-注释

推荐答案

正如我所说,你在重定向页面时通过了id.您需要在<router-link>标记中传递title键.

{path: "/products/:title", name: "Product", component: Product}

<router-link :to="`/products/${product.title}`">
   <img
     :src="product.photo"
     alt="Placeholder image"
   >
</router-link>

完成后,您将拥有这个URL http://localhost:8080/products/galaxy-note.

确保在product对象的title键中得到的任何值都将附加到URL中.

接下来要注意的是,在脚本标记的mounted挂钩中使用axios调用API时.你在params中得不到id分.您将在params对象中获得title,因此您也需要更新该代码.

EDIT 1:如果您正在接收带有空格(如galaxy note)的值,并且希望url中有galaxy-note,那么您可能需要使用replace函数将spaces替换为-,然后再将其传递给<router-link>标记.

Vue.js相关问答推荐

无法从CDN使用Vue和PrimeVue呈现DataTable

虚拟DOM在Vue中姗姗来迟

Vuetify 3 v-radio-group 将模型设置为 null

我如何使用vuejs访问彼此嵌套的json对象

在Vue 2中,是否可能在不创建组件的情况下注入代码块?

我在 nuxt2 中看不到索引页

如何使用 Vite 从公共目录导入 JSON 文件?

Vue CLI - 编译后将配置文件保留为外部

Vuetify 置顶工具栏

如何在Typescript语言Vuejs中使用watch功能?

为什么 Vue 路由/Webpack 开发服务器现在在页面刷新时显示无法获取/路径?

如何在某些异步数据(在 Vuex 存储中)加载之前防止任何路由?

Vue&TypeScript:在项目目录外的 TypeScript 组件中实现导入时如何避免错误 TS2345?

为什么 vue 文档说 refs 不是响应式的,而实际上它们是响应式的

Vue Chart.js - 条形图上的简单点/线

将登录页面包含在单页应用程序中是否不安全?

Vue.js 中的 CSS 框架

无法访问函数内的数据属性

错误:找不到模块'@vue/babel-preset-app'

标签中的 href 赋值