vuex
? ? ? vuex解決不同組件的數(shù)據(jù)共享,數(shù)據(jù)持久化。
? ? ? 1.安裝:
? ? ? ? npm install vuex --save
? ? ? 2.在main.js導入包
? ? ? ? import Vuex from 'vuex'
? ? ? 3.在main.js注冊包
? ? ? ? Vue.use(vuex)
? ? ? 4.在main.js里面new Vuex.store實例,得到一個倉儲對象。
? ? ? ? var store = new Vuex.Store({
? ? ? ? ? state:{
? ? ? ? ? ? //state是組件中的data,專門用來存儲數(shù)據(jù)的
? ? ? ? ? ? count: 0 //全局有一個0數(shù)據(jù)
? ? ? ? ? ? //如果在組件中想要訪問store中的數(shù)據(jù),只能通過this.$store.state.***來訪問
? ? ? ? ? ? //例如訪問上面0:<input type="text" v-model="$store.state.count">
? ? ? ? ? },
? ? ? ? ? mutations: {//mutations是方法,主要用于·
? ? ? ? ? ? //如果要操作store中的state值,只能通過調(diào)用mutations提供的方法,才能操作對用的數(shù)據(jù)
? ? ? ? ? ? //不推薦直接操作state中的數(shù)據(jù),因為萬一導致數(shù)據(jù)紊亂,不能快速定位到錯誤的原因,因為,每個組件都可能有操作數(shù)據(jù)的方法;
? ? ? ? ? ? increment(state){? //increment是方法名,第一個參數(shù)state是規(guī)定死的。
? ? ? ? ? ? ? state.count++
? ? ? ? ? ? ? }
? ? ? ? ? ? ? //注意:如果組件想要調(diào)用mutations中的方法,只能使用this.$store.commit('方法名')
? ? ? ? ? ? ? //這種調(diào)用mutations方法的格式,和this.$emit('父組件中方法名')
? ? ? ? ? }
? ? ? ? })?
? ? ? 5.在main.js里面掛載store(和掛載路由一樣)
? ? ? ? const vm = new Vue({
? ? ? ? ? el: '#app',
? ? ? ? ? render: c => c(app),
? ? ? ? ? router //掛載路由
? ? ? ? ? store //將vuex創(chuàng)建的store 掛載到VM實例上。
? ? ? ? ? //只要掛載到vm上,任何組件都能使用store來存取數(shù)據(jù)
? ? ? ? })
? ? ? ? vuex的使用:
? ? ? ? 1、src目錄下面新建一個vuex的文件夾
? ? ? ? 2、vuex 文件夾里面新建一個store.js
? ? ? ? 3、安裝vuex?
? ? ? ? ? cnpm install vuex --save
? ? ? ? 4、在剛才創(chuàng)建的store.js引入vue? 引入vuex 并且use vuex
? ? ? ? ? import Vue from 'vue'
? ? ? ? ? import Vuex from 'vuex'
? ? ? ? ? Vue.use(Vuex)
? ? ? ? 5、定義數(shù)據(jù)
? ? ? ? ? ? /*1.state在vuex中用于存儲數(shù)據(jù)*/
? ? ? ? ? ? var state={
? ? ? ? ? ? ? ? count:1
? ? ? ? ? ? }
? ? ? ? 6、定義方法?? mutations里面放的是方法,方法主要用于改變state里面的數(shù)據(jù)
? ? ? ? ? var mutations={
? ? ? ? ? ? ? incCount(){
? ? ? ? ? ? ++state.count;
? ? ? ? ? ? ? }
? ? ? ? ? }
? ? ? ? 暴露
? ? ? ? ? const store = new Vuex.Store({
? ? ? ? ? ? ? state,
? ? ? ? ? ? ? mutations
? ? ? ? ? })
? ? ? ? ? export default store;
? ? ? ? 組建里面使用vuex:
? ? ? ? ? 1.引入 store
? ? ? ? ? ? import store from '../vuex/store.js';
? ? ? ? ? 2、注冊
? ? ? ? ? ? export default{
? ? ? ? ? ? ? data(){
? ? ? ? ? ? ? ? ? return {? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ? msg:'我是一個home組件',
? ? ? ? ? ? ? ? value1: null,
? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? },
? ? ? ? ? ? ? store,? //注冊
? ? ? ? ? ? ? methods:{
? ? ? ? ? ? ? ? ? incCount(){
? ? ? ? ? ? ? ? this.$store.commit('incCount');? /*觸發(fā) state里面的數(shù)據(jù)*/
? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? 3、獲取state里面的數(shù)據(jù)?
? ? ? ? ? ? this.$store.state.數(shù)據(jù)名
? ? ? ? ? 4、觸發(fā) mutations 改變 state里面的數(shù)據(jù)
? ? ? ? ? ? this.$store.commit('incCount');