VUE使用vuex解决模块间传值问题的方法
2017-06-01 16:05
776 查看
在看电影、打Dota、撸代码间来回,犹豫不决,终于还是下决心继续学习VUE。
仿照 conde.js 官网写的一个demo,目前已经基本可用,但始终缺少登录页,没有用户权限管理,于是开撸......
<template> <div id="login"> <c-header></c-header> <c-form></c-form> <p class="content-block"><a href="javascript:;" rel="external nofollow" rel="external nofollow" @click=showState class="button button-fill button-success">登录</a></p> </div> </template>
外观大概是这样的:
两个输入项通过 c-form 组件导入
由于没有登录接口调用,初步想法是:点击登录,将c-from组件输入的值(用户名和密码)保存在 sessionStorage 中,通过判断 sessionStorage 是否保存了用户信息,来决定用户的操作权限。
现在问题来了――点击登录,如何取得 c-form 组件中的输入值?
最直接的想法就是通过子组件派生事件,父组件监听触发。转念一想,何不使用vuex来进行管理呢?正好之前从来没有认真对待过它。
LOL......
坑坑坑,我踩踩踩
终于,总结出使用 vuex 的三大步骤:
步骤1:安装和创建
安装 vuex:npm i vuex --save
创建 store.js,把基本格式写好:
import Vue from 'vue' import Vuex from 'vuex' // 首先声明一个状态 state const state = { msg: '' } // 然后给 actions 注册一个事件处理函数,当这个函数被触发时,将状态提交到 mutaions中处理 const actions = { saveName({commit}, msg) { commit('saveMsg', msg) // 提交到mutations中处理 } } // 更新状态 const mutations = { saveMsg(state, msg) { state.msg = msg; } } // 获取状态信息 const getter = { showState(state) { console.log(state.msg) } } // 下面这个相当关键了,所有模块,记住是所有,注册才能使用 export default new Vuex.Store{ state, getter, mutations, actions }
步骤2:在子组件中使用(保存输入)
具体到我这里,是在c-form中使用它:
<template> <div> <input type="text" @blur=saveName(username) v-model="username" placeholder="Your name"> </div> </template> <script type="text/javascript"> // 引入mapActions,很重要 import { mapActions } from 'vuex' export default { data() { return { username:'', password: '' } }, methods: { ...mapActions({ // 在input 的blur 事件中触发回调,并将输入值作为参数返回到store中 saveName: 'saveName' }) } } </script>
步骤3:获取在步骤2 中的输入值(获取state)
<template> <div id="login"> <c-header></c-header> <c-form></c-form> <p class="content-block"><a href="javascript:;" rel="external nofollow" rel="external nofollow" @click=showState class="button button-fill button-success">登录</a></p> </div> </template> <script> // 引入mapGtters,很重要 import { mapGetters } from 'vuex' export default { methods: { ...mapGetters([ // 在store.js 中注册的getters 'showState' ]) }, components: { "c-form": require('../components/form.vue'), "c-header": require('../components/header.vue') } } </script>
至此,我们就能得到输入值了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
相关文章推荐
- [vuex]——使用vuex解决模块间传值问题
- vue-cli的axios使用方法,get、post请求的跨域问题解决
- vue 2.0中使用axios遇到问题的解决方法
- SpringBoot+Vue前后端分离,使用SpringSecurity完美处理权限问题的解决方法
- Vue-router本地服务器使用history出现找不到页面的问题解决方法
- Python使用urllib模块的urlopen超时问题解决方法
- 使用Vuex解决Vue中的身份验证问题
- 在安装并使用tensorflow中的Object-detection模块时遇到的一些问题汇总及解决方法
- Vue使用vux-ui自定义表单验证遇到的问题及解决方法
- 使用vue-router与v-if实现tab切换遇到的问题及解决方法
- vue中axios解决跨域问题和拦截器的使用方法
- vue中使用iview自定义验证关键词输入框问题及解决方法
- CSV模块使用时的几个问题及解决方法
- 解决vue-cli中stylus无法使用的问题方法
- Firefox 使用常见问题和解决方法
- Infragistics的NetAdvantage控件使用中遇到的问题及解决方法
- 关于在使用Exchange2003系统时无法向sina,yahoo,hotmail等邮箱发送邮件问题的解决方法
- 使用ld的“-Ttext”选项时可能产生的一个问题的解决方法
- [原创]SQL Server 2005:一个使用新创建的User的问题和解决方法