Vue 3 -手表中的值发生变化时的手表

6mzjoqzu  于 2023-01-26  发布在  Vue.js
关注(0)|答案(1)|浏览(209)

我有一个监视器,我正在其中更改activeTable的值-此值存储在Pinia存储中:

const { tables, freeTables, usedTables, activeTable, selectedTable } = storeToRefs(useTableStore())

watch([tables, urlPath], (newValue, oldValue) =>
  {
    if(urlPath.value[0] === 'tables' && Number.isInteger(+urlPath.value[1]))
    {

      let tableIndex = tables.value.findIndex(table =>
        +table.id ===  +urlPath.value[1]
      )

      if(tableIndex > -1)
      {
        let table = tables.value[tableIndex]

        if(+table.userID === +userData.id || +table.waiterID === +userData.id)
        {
          mineButton.click();
        }
        else
        {
          document.getElementById('other-tables').click()
        }

         activeTable.value = table

      }
    }
  })

在另一个组件中,我正在查看activeTable

const {showTableOrder, activeTable, selectedTable} = storeToRefs(useTableStore())

watch(
        () => activeTable.value,
        async (newValue, oldValue) => {
            console.log(newValue);
            console.log(oldValue);
        },
        { deep: true }
    )

如果刷新页面,第一个监视器按预期工作,并且activeTable设置正确,但是第二个监视器从未激活。

fhg3lkii

fhg3lkii1#

如果希望监视器在初始化时触发,请从watch语句中删除.value,并将immediate: true添加到选项中:

watch(
  () => activeTable,  // no ".value", you want to watch the ref
  async (newValue, oldValue) => {
    ...
  },
  {
    deep: true,
    immediate: true, // execute watch on initialization
  }
)

相关问题