1

我正在 vue.js + firebase 中开发一个类似 Messenger 的应用程序。我想做的是 - 在每次路由更改时,从 db 中获取一些对应于 id(存储在路由中)的数据,然后将其显示在屏幕上。我对这些数据有一些奇怪的行为,但它并没有按预期工作。

编码:

  methods: {
    getRoomName() {
      db.collection("rooms")
        .doc(this.params)
        .onSnapshot((snapshot) => (this.roomName = snapshot.data().name));
    },
  },
  watch: {
    $route(to, from) {
      this.getRoomName();
    },
  },

其中数据:

data() {
    return {
      input: "",
      roomName: "",
      params: this.$route.params.id,
      message: "",
      roomNameTest: "",
    };
  },

模板:<span class="roomName">{{roomName}}</span>

4

3 回答 3

0

我注意到的第一件事是您在 data() 处调用 this.$route,它不起作用。如果您需要填充某些内容,请尝试使用Vue Lifecycle Hooks

于 2020-09-16T13:08:31.530 回答
0

生命周期钩子(挂载/创建)是针对这类事情的。它们分别在创建和挂载 vue 实例时调用。

mounted() // it can also work for the created hook {
  this.getRoomName();
},

watcher 监视路由变化,但并不真正适合这种情况,因为当路由更改时,它正在监视的组件尚未实例化。当您正在观看的特定 Vue 实例分别被实例化/挂载时,将触发挂载/创建的钩子。

如果 url 上的参数发生更改并且您需要做一些事情,则使用观察者进行路由更改的适当时间。一个例子是改变/users/1 to /users/2`。这将起作用,因为使用了相同的组件并且观察者将检测到更改。

于 2020-09-16T13:18:03.073 回答
0

我正在使用$route.path来监视更改以获取新 ID。

零件

  computed: {
    ...mapState('products', ['products']),
  },
  watch: {
    '$route.path'() {
      this.bindProducts(this.IdFromUrl)
    },
  },

  mounted() {
    this.bindProducts(this.IdFromUrl)
  },

  methods: {
    ...mapActions('products', ['bindProducts']),
  }

在我的商店里运行的是 vuexfire。或者,您可以绑定自己的数据。

于 2020-10-02T21:18:38.333 回答