Vue


pinia

<p><strong>pinia 比 vuex 简单一点</strong></p> <pre><code class="language-javascript">import './assets/main.css' import { createApp } from 'vue' import { createPinia } from 'pinia' import App from './App.vue' import router from './router' const app = createApp(App) app.use(createPinia()) app.use(router) app.mount('#app')</code></pre> <p><strong>存储数据</strong></p> <pre><code class="language-javascript">import { ref, computed } from 'vue' import { defineStore } from 'pinia' export const useCounterStore = defineStore('counter', () =&amp;gt; { const count = ref(0) const name = ref('Andy') const doubleCount = computed(() =&amp;gt; count.value * 2) function increment() { count.value++ } return { count, name, doubleCount, increment } }) </code></pre> <p><strong>读取数据</strong></p> <pre><code class="language-javascript">import { useCounterStore } from './stores/counter' let counterStore = useCounterStore() console.log(counterStore.count) // 0</code></pre> <p><strong>修改数据1:一个一个改</strong></p> <pre><code class="language-javascript">import { useCounterStore } from './stores/counter' let counterStore = useCounterStore() counterStore.count++ counterStore.name = &amp;quot;Curry&amp;quot; console.log(counterStore.count) // 1 console.log(counterStore.name)  // Curry</code></pre> <p><strong>修改数据2:批量改</strong></p> <pre><code class="language-javascript">import { useCounterStore } from './stores/counter' let counterStore = useCounterStore() counterStore.$patch({ count: 1, name: &amp;quot;Curry&amp;quot; }) console.log(counterStore.count) // 1 console.log(counterStore.name) // Curry</code></pre> <p><strong>修改数据3:用 pinia 里的方法改</strong></p> <pre><code class="language-javascript">import { useCounterStore } from './stores/counter' let counterStore = useCounterStore() counterStore.increment() console.log(counterStore.count) // 1</code></pre> <p><strong>storeToRefs:使接收过来的数据具有响应式</strong> storeToRefs 和 toRefs 的区别是,storeToRefs 只关注 store 的数据,不会对方法进行 ref 包裹</p> <pre><code class="language-javascript">import { useCounterStore } from './stores/counter' import { storeToRefs } from 'pinia' let counterStore = useCounterStore() let { count, name } = storeToRefs(counterStore) function add() { counterStore.count++ }</code></pre> <p><strong>subscribe:监听 stroe 数据的变化</strong> 有点像 computed 但是 template 中不用有被监听的数据</p> <pre><code class="language-javascript">import { useCounterStore } from './stores/counter' let counterStore = useCounterStore() counterStore.$subscribe((mutate, state) =&amp;gt; { console.log(&amp;quot;监听到了store的变化&amp;quot;) console.log(state.count) }) function add() { counterStore.count++ }</code></pre>

页面列表

ITEM_HTML