对vuex的一点理解
生活随笔
收集整理的這篇文章主要介紹了
对vuex的一点理解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
vuex是vue.js的一個狀態管理工具,它適用于解決平行組件之間的數據共享問題。一般情況下,我們更多的是父子組件之間通過props或$emit來實現傳值,如何不滿足以上情況那只有使用vuex進行解決。廢話不多說,直接上代碼。
1.先安裝vuex
npm install vuex --save
2.創建一個store的文件夾,新建store.js文件。我們需要在這個文件中引入Vue和Vuex,并且需要安裝Vuex
import Vue from 'vue'; import Vuex from 'vuex';Vue.use(Vuex);const state={count:1 }const mutations={add(state,n){state.count+=n;},reduce(state){if(state.count<=1){state.count=1;}else{state.count-=1; }} }export default new Vuex.Store({state,mutations})State中放我們需要共享的數據,mutations是用來處理數據的方法。
3.創建視圖組件來調用store中的方法
<template><div><h2>{{msg}}</h2><hr/><h3>{{$store.state.count}}</h3><div><button @click="$store.commit('add',10)">+</button><button @click="$store.commit('reduce')">-</button></div></div> </template> <script>import store from "@/store/store"export default{data(){return{msg:'Hello Vuex'}},store,computed:{count(){return this.$store.state.count}}} </script> <style scoped></style>這樣一個簡單的vuex例子就完成了。
我們還可以有別的寫法來完成上述的功能
import Vue from 'vue'; import Vuex from 'vuex';Vue.use(Vuex);const state={count:1 }const mutations={add(state,n){state.count+=n;},reduce(state){if(state.count<=1){state.count=1;}else{state.count-=1; }} }const actions={"INC":(store)=>{store.commit('add',10)},"RED":(store)=>{store.commit('reduce')}} export default new Vuex.Store({state,mutationsactions })在store.js中定義一個actions用來負責把mutations中的邏輯發送給視圖
<template><div><h2>{{msg}}</h2><hr/><h3>{{$store.state.count}}</h3><div><button @click="add">+</button><button @click="reduce">-</button></div></div> </template> <script>import store from "@/store/store"export default{data(){return{msg:'Hello Vuex'}},store,computed:{count(){return this.$store.state.count}},methods:{add:function(){this.$store.dispatch("INC")},reduce:function(){this.$store.dispatch("RED")}}} </script> <style scoped></style>
不足之處,希望多多指正~~
?
轉載于:https://www.cnblogs.com/linxing/p/8443862.html
總結
以上是生活随笔為你收集整理的对vuex的一点理解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JAVA知识积累 JSP第一篇【JSP介
- 下一篇: 不擅演讲的马化腾在 08 年讲了什么?