我正试图在我的浏览器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

在 Nuxt3 中使用 Vue3 vue-ganntastic 插件

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

Vuejs 通过数据键迭代复杂对象

点击屏幕的任何位置都会禁用v-overlay

在 v-for 中定义变量有什么问题吗?

vue js导航到带有问号的url

使用带有 v-date-picker 的 new Date() 不起作用

VueJs this.method 不是函数?如何在 Vuejs 的另一个方法中调用一个方法?

如何使用 laravel-mix 将 bootstrap-vue 加载到 Laravel 5 中?

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

Vue更改宽度和内容

Javascript/vue.js 接收json

Vue 3 组合 API,如何在 setup() 函数中获取上下文父属性?

Vue:如何在按钮单击时调用 .focus()

Vue 3:模块 '"../../node_modules/vue/dist/vue"' 提示

如何使用 JavaScript 按索引删除数组元素?

按键删除对象不会更新vue组件

在 vue js 中的何处以及如何存储 API 端点?

在~/components/AddPlaceModal.vue中找不到导出AddPlaceModal