vuex下state数据的存储

来源:互联网 发布:万得数据 编辑:程序博客网 时间:2024/05/29 17:10

1。在src文件下创建一个store文件,里面加入一个store.js文件
。内容大致为

import vuex from 'vuex'import Vue from 'vue'Vue.use(vuex)export default new vuex.Store({    /*state必须*/    state:{        user:{}    },    mutations:{        setUser(state,v){            state.user=v;        }    }})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

2。在main.js中的vue实例中必须引入,例

import Vue from 'vue'import App from './App'import router from './router'import ElementUI from 'element-ui'import 'element-ui/lib/theme-default/index.css'import * as api from './config'import mycom from './components/index'import store from './store/store'Vue.prototype.$api = apiVue.config.productionTip = falseVue.use(ElementUI)Vue.use(mycom)Vue.test = function () {  alert()}/* eslint-disable no-new */new Vue({  el: '#app',  router,  store:store,  template: '<App/>',  components: { App }})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

3。在看在哪里引用setUser方法,例如在login.vue中引用,一般在methods中会用到,如

<template>  <div>    <el-input v-model="user.username"></el-input>    <el-input v-model="user.password"></el-input>    <el-input v-model="user.checkcode"></el-input>    <img :src="codeurl" alt="">    <!--<el-button type="sucess" @click="loginUser">提交</el-button>-->   <!-- <a href="#/demo/111">111</a>    <a href="#/demo/222">222</a>-->    <router-link to="/demo/222">2222</router-link>    <router-link to="/demo/111">1111</router-link>  </div></template><script>  export default{    data () {      return {        user: {          username: '',          password: '',          checkcode: ''        },        codeurl: ''      }    },    methods: {      loginUser () {        this.$store.commit('setUser',this.user)        this.$router.push('/demo/11')        /*this.$api.login(this.user).then(function (res) {          console.log(res.data)        })*/      }    }  }</script><style scoped></style>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

其中setUser名字必须对应,名字随意,但最好为英文
新手上路,不习勿喷
http://blog.csdn.net/github_26672553/article/details/53265126

(function () {('pre.prettyprint code').each(function () { var lines = (this).text().split(\n).length;varnumbering = $('
    ').addClass('pre-numbering').hide(); (this).addClass(hasnumbering).parent().append(numbering); for (i = 1; i
原创粉丝点击