pinia 的值在vue页面中如何监听变化
时间: 2024-02-21 14:59:13 浏览: 91
要监听 Pinia Store 中的值的变化,可以使用 `watch` API 或者 `computed` API。以下是两种方法的示例:
1. 使用 `watch` API:
```javascript
import { defineComponent, watch } from 'vue'
import { useStore } from 'pinia'
export default defineComponent({
setup() {
const store = useStore()
watch(
() => store.state.piniaValue,
(newVal, oldVal) => {
console.log(`Pinia value changed from ${oldVal} to ${newVal}`)
}
)
return {}
}
})
```
2. 使用 `computed` API:
```javascript
import { defineComponent, computed } from 'vue'
import { useStore } from 'pinia'
export default defineComponent({
setup() {
const store = useStore()
const piniaValue = computed(() => store.state.piniaValue)
function handlePiniaValueChange(newVal, oldVal) {
console.log(`Pinia value changed from ${oldVal} to ${newVal}`)
}
watch(piniaValue, handlePiniaValueChange)
return {}
}
})
```
以上两种方法都可以监听 Pinia Store 中的值的变化,具体使用哪种方法取决于你的需求和偏好。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)