Skip to content

Instantly share code, notes, and snippets.

@bin-r00t
Last active May 30, 2024 06:37
Show Gist options
  • Save bin-r00t/61dfcd2f35870f9b43e5083e5a6aadf0 to your computer and use it in GitHub Desktop.
Save bin-r00t/61dfcd2f35870f9b43e5083e5a6aadf0 to your computer and use it in GitHub Desktop.
vue3 - storeToRefs()
<script setup>
import { watch } from 'vue';
import { storeToRefs } from 'pinia';
import { useCounterStore } from '@/stores/counter.js';
const store = useCounterStore();
const { count } = storeToRefs(store);
console.log('count===>', count);
// 这上面的 count 会不会随着 store 里 count 的更新而自动响应?
// 答: 经实践,会。而且不论 store 是用 选项方式 定义的还是 组合函数方式 定义的
// gists: https://gist.github.com/bin-r00t/61dfcd2f35870f9b43e5083e5a6aadf0
// 而非猜想的:"这里的count只响应本组件内的变化。"那样
setTimeout(() =>{
store.increment(100);
}, 2000);
watch(count, val =>{console.log('count changed: ', val)});
</script>
<template>
<h1>{{ count }}</h1>
</template>
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state(){
return {
count:0
}
},
getters: {
doubleCount: state => state.count * 2,
},
actions:{
increment(num) {
this.count += num;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment