zoukankan      html  css  js  c++  java
  • Vuex


    1. vue中各个组件之间传值

    1.父子组件

    父组件-->子组件,通过子组件的自定义属性:props

    子组件-->父组件,通过自定义事件:this.$emit('事件名',参数1,参数2,...);

    2.非父子组件或父子组件

    通过数据总数Bus,this.$root.$emit('事件名',参数1,参数2,...)

    3.非父子组件或父子组件

    更好的方式是在vue中使用vuex

    方法1: 用组件之间通讯。这样写很麻烦,并且写着写着,估计自己都不知道这是啥了,很容易写晕。

    方法2: 我们定义全局变量。模块a的数据赋值给全局变量x。然后模块b获取x。这样我们就很容易获取到数据

    2. Vuex

    官方解释:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。可以想象为一个“前端数据库”(数据仓库),让其在各个页面上实现数据的共享包括状态,并且可操作

    Vuex分成五个部分: 

    1.State:单一状态树

    2.Getters:状态获取

    3.Mutations:触发同步事件

    4.Actions:提交mutation,可以包含异步操作

    5.Module:将vuex进行分模块

    3. vuex使用步骤

    3.1 安装

    npm install vuex -S

    3.2 创建store模块,分别维护state/actions/mutations/getters

    store  

     index.js

     State.js  

     Sctions.js

     Sutations.js

     Setters.js

    3.3 在store/index.js文件中新建vuex的store实例,并注册上面引入的各大模块

    import Vue from 'vue'
    import Vuex from 'vuex'
    import state from './State'
    import getters from './Getters'
    import actions from './Actions'
    import mutations from './Mutations'
    Vue.use(Vuex)
    const store = new Vuex.Store({
         state,
         getters,
         actions,
         mutations
     })
    
     export default store

    3.4 在main.js中导入并使用store实例

    // The Vue build version to load with the `import` command
    // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
    import Vue from 'vue'
    // process.env.MOCK && require('@/mock')
    import 'element-ui/lib/theme-chalk/index.css'
    import App from './App'
    import router from './router'
    import ElementUI from 'element-ui'
    import axios from '@/api/http'
    // import axios from 'axios'
    import VueAxios from 'vue-axios'
    import store from './store'//新加
    
    Vue.use(VueAxios,axios)
    Vue.use(ElementUI)
    Vue.config.productionTip = false
    
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      data(){
       return {
         Bus:new Vue({
    
         })
       }
      },
      router,
      store,//新加
      components: { App },
      template: '<App/>'
    })

    3.5 之后按要求编码,即可使用vuex的相关功能

    4. vuex的核心概念:store、state、getters、mutations、actions

     Store

    每一个Vuex应用的核心就是store(仓库),store基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。

    const store = new Vuex.Store({
    
      state, // 共同维护的一个状态,state里面可以是很多个全局状态
    
      getters, // 获取数据并渲染
    
      actions, // 数据的异步操作
    
      mutations // 处理数据的唯一途径,state的改变或赋值只能在这里
    
    })

    4.1 State(保存数据的容器)

    状态,即要全局读写的数据

    const state = {
    
    resturantName:'飞歌餐馆'
    
    };

    this.$store.state.resturantName;//不建议

    4.2 Getters

    获取数据并渲染,

    export default {
      getResturantName: (state) => {
        return state.resturantName;
      }
    }

    注1:getters将state中定义的值暴露在this.$store.getters对象中,我们可以通过如下代码访问
    this.$store.getters.resturantName

    注2:state状态存储是响应式的,从store实例中读取状态最简单的方法就是在计算属性中返回某个状态,如下:

    computed: {
      resturantName: function() {
        return this.$store.getters.resturantName;
      }
    }


    4.3 Mutations

    处理数据的唯一途径,state的改变或赋值只能在这里

    export default{
      // type(事件类型): 其值为setResturantName
      // payload:官方给它还取了一个高大上的名字:载荷,其实就是一个保存要传递参数的容器
      setResturantName: (state, payload) => {
                state.resturantName = payload.resturantName;
      }
    }

    注1:mutations中方法的调用方式
    不能直接调用this.$store.mutations.setResturantName('KFC'),必须使用如下方式调用:
    this.$store.commit(type,payload);

    // 1、把载荷和type分开提交
    store.commit('setResturantName',{
    resturantName:'KFC'
    })
    // 2、载荷和type写到一起
    store.commit({
    type: 'setResturantName',
    resturantName: 'KFC'
    })

    注2:一定要记住,Mutation 必须是同步函数。为什么呢?异步方法,我们不知道什么时候状态会发生改变,所以也就无法追踪了
    如果我们需要异步操作,Mutations就不能满足我们需求了,这时候我们就需要Actions了

    mutations: {
      someMutation (state) {
        api.callAsyncMethod(() => {
        state.count++
        })
      }
    } 

    6. actions 

    export default {
      setResturantNameByAsync: (context, payload) => {
        console.log('xxxx');
        setTimeout(() => {
          console.log('yyyy');
          console.log(payload)
          // state.resturantName = payload.resturantName;
          context.commit('setResturantName', payload); //Action提交的是mutation
        }, 6000)
        console.log('zzzz');
      },
      doAjax: (context, payload) => {
        let _this=payload._this
        let url = _this.axios.urls.SYSTEM_USER_DOLOGIN;
        // let url = 'http://localhost:8080/T226SSH/vue/userAction_login.action';
        _this.axios.post(url, {}).then((response) => {
          console.log(response);
        }).catch(function(error) {
          console.log(error);
        });
      }
    
    }

     vuex综合案例

    需求:两个组件A和B,vuex维护的公共数据是餐馆名:resturantName,默认值:飞歌餐馆,

    那么现在A和B页面显示的就是飞歌餐馆。如果A修改餐馆名称为A餐馆,则B页面显示的将会是A餐馆,反之B修改同理。

    这就是vuex维护公共状态或数据的魅力,在一个地方修改了数据,在这个项目的其他页面都会变成这个数据。

    代码实例:

    VuePage1.vue

    <template>
      <div>
        <h3>页面1:欢迎来到{{msg}}</h3>
        <button @click="buy">盘他(同步)</button>
        <button @click="buyAsync">搞他(异步)</button>
        <button @click="doAjax">搞他(异步)</button>
    
      </div>
    </template>
    
    <script>
      export default {
        data() {
          return {
    
          };
        },
        computed: {
          msg() {
            return this.$store.state.resturantName;
          }
        },
        methods: {
          buy() {
            this.$store.commit('setResturantName', {
              resturantName: 'KFC'
            })
          },
          buyAsync() {
            this.$store.dispatch('setResturantNameByAsync', {
              resturantName: 'KFC'
            })
          },
          doAjax(){
    
          }
        }
      }
    </script>
    
    <style>
    </style>

    VuePage1.vue

    <template>
      <div>
        <h3>欢迎来到{{msg}} </h3>
      </div>
    </template>
    
    <script>
      export default {
        data() {
          return {
    
          };
        },
        computed: {
          msg() {
            return this.$store.getters.getResturantName;
          }
        }
      }
    </script>
    
    <style>
    </style>

    效果如下:

     

  • 相关阅读:
    Ajax
    对于本地上关联了远程的git上的项目,删除现有的关联,然后关联新创建的git项目
    UNI-APP_uni-simple-router的快速上手(路由,nui路由拦截)
    js之观察者模式和发布订阅模式区别
    Vue CLI 3.0脚手架如何在本地配置mock数据
    es6解构赋值和扩展运算符
    js Array数组详细操作方法及解析合集
    list排序
    java常用的object数据处理
    java 读写 txt 文件
  • 原文地址:https://www.cnblogs.com/huxiaocong/p/11478796.html
Copyright © 2011-2022 走看看