vuejs 问题更改路由在 localstorage 中获取 userChoice 但在获取新 userChoice 之前推送配置文件路由?

时间:2020-12-29 12:47:39

标签: vue.js vuejs2

问题是,在点击时,我会根据选择的用户增加新的 userChoice,但它会在检索新的 userChoice 点击之前推送配置文件路由。

这里要做的是我的模板我将把所有内容都放在同一个函数中更改最后使用 push 但它也不起作用然后我做了 2 个函数但它也不起作用 解决方案是什么??

<template>
  <section
    class="stopPadMarg container-fluid d-md-flex justify-content-between"
  >
    <div class="py-5 stopPadMarg bg-primary col-md-1">
      <img
        src="../assets/image/icon.png"
        width="60px"
        class="rounded-circle"
        alt="logo"
      />
    </div>
    <div class="largeur80">
      <form class="justify-content-center form-inline py-3 my-2 my-lg-0">
        <input
          v-model="searchKey"
          id="search"
          class="form-control mr-sm-2"
          type="search"
          placeholder="Search"
          aria-label="Search"
        />
      </form>
      <div>
        <h3
          class="backPrimaire opacity mx-1 text-primary bordurePost bordureRond"
        >
          <b-icon-chevron-double-down
            class="mr-5 my-1 pt-1 text-secondary"
            animation="cylon-vertical"
            font-scale="1"
          ></b-icon-chevron-double-down>
          Vos collegues
          <b-icon-chevron-double-down
            class="ml-5 my-1 pt-1 text-secondary"
            animation="cylon-vertical"
            font-scale="1"
          ></b-icon-chevron-double-down>
        </h3>
      </div>
      <div class="hauteur">
        <div class="mt-5 d-flex flex-wrap">
          <div
            v-for="(user, id) in filteredList"
            v-bind:key="id"
            class="col-md-3 d-flex flex-column align-items-center align-content-center"
          >
            <div @click="changeUser(user)" class="cursor">
              <img
                @click="changeRoute"
                v-if="user.image_url !== null || ''"
                :src="user.image_url"
                width="100px"
                height="100px"
                class=" justify-content-left bordureProfil
          rounded-circle"
              />
              <img
                v-else
                src="../assets/image/icon.png"
                width="100px"
                class=" justify-content-left bordureProfil rounded-circle"
              />
            </div>
            <div>
              <h5 class="mt-2">
                {{ user.nom.toUpperCase() }}
              </h5>
              <h6 class="mb-3">{{ user.prenom.toLowerCase() }}</h6>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="py-5 stopPadMarg bg-primary col-md-1">
      <img
        src="../assets/image/icon.png"
        width="60px"
        class="rounded-circle"
        alt="logo"
      />
    </div>
  </section>
</template>
<script>
import axios from "axios";
export default {
  components: {},
  data() {
    return {
      searchKey: "",
      postes: [],
      users: [],
      user_id: localStorage.getItem("userId"),
      userChoice: localStorage.getItem("userChoice"),
    };
  },
  async created() {
    this.postes = [];
    this.users = [];

    await axios
      .get("http://localhost:3000/postes")
      .then(
        (response) => ((this.postes = response.data), console.log(response))
      )
      .catch((error) => console.log(error));

    await axios
      .get("http://localhost:3000/users")
      .then(
        (response) => ((this.users = response.data), console.log(this.users))
      )
      .catch((error) => console.log(error));

    await axios
      .get("http://localhost:3000/users")
      .then(
        (response) => (
          (this.userDef = response.data.find((user) => {
            return user.id;
          })),
          console.log(this.userDef)
        )
      )
      .catch((error) => console.log(error));

    await axios
      .get(`http://localhost:3000/user/${this.user_id}`)
      .then(
        (response) => (
          (this.userConnect = response.data), console.log(this.userConnect.id)
        )
      )
      .catch((error) => console.log(error));

    await axios
      .get("http://localhost:3000/commentaires")
      .then(
        (response) => (
          (this.comments = response.data), console.log(this.comments)
        )
      )
      .catch((error) => console.log(error));
  },

  computed: {
    filteredList() {
      return this.users.filter((user) => {
        return user.nom.toLowerCase().includes(this.searchKey.toLowerCase());
      });
    },
  },
  methods: {
    async changeUser(user) {
      await localStorage.removeItem("userChoice");
      await localStorage.setItem("userChoice", user.id);

      this.$router.push(`/profil/${this.userChoice}`);
    },
    async changeRoute() {
      await this.$router.push(`/profil/${this.userChoice}`);
    },
  },
};
</script>

<style></style>

和这里的图片

如果我在同一个个人资料上第二次按下它,如果我返回同事页面,它就会给我,但如果我更改个人资料,则会出现一个空白页面

enter image description here enter image description here

enter image description here

这里是路线图

enter image description here

事实上,路线并没有改变配置文件,而是保留在 58 此处 c 连接的配置文件,如果我们更改路线上的号码,它会启动一个页面页面,因此这是路线路径的问题我们在浏览器缓存中看到

1 个答案:

答案 0 :(得分:0)

查看您的代码后,很明显为什么您在更改路线时会得到一个空白页面。让我解释一下:

您的路线是这样说的: 注册路由 /profil/${userChoice} (这是从 localStorage 读取的值)。 此路由定义仅在页面初始化时读取一次。因此,当您的页面加载时,只会定义 /profil/58,而不会定义 /profil/59。

您可能正在寻找的是路由参数:

https://router.vuejs.org/guide/essentials/dynamic-matching.html

您希望此 url 的数字部分是动态的并响应更改。

因此,不是从 localStorage 读取值,您应该这样写:

{ 
    path: '/profil/:user_id', 
    name: 'ProfilUser', 
    ...
}

现在,当您的 Profil 组件被初始化而不是访问 localStorage 时,您将读取提供的值,如下所示:

created() {
    var userChoice = this.$route.params.user_id;
}

(请注意,也可以将此参数作为道具获取,请参阅 vue-router 文档以了解如何执行此操作)

您需要记住的另一件事是,您需要在此参数更改时做出响应。您的组件将不会被刷新/重新安装。

要响应参数更改,您可以执行以下操作:

watch: {
   '$route.params.user_id'() { 
       this.reloadAllStuff();
   }
}

我建议不要在这个用例中使用 localStorage,让 URL 参数成为主要的事实来源。

进一步阅读:

相关问题