• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
LDLX@Y火星
博客园    首页    新随笔    联系   管理    订阅  订阅

vuex使用一

至于为什么使用vuex在这里就不过多的解释了,直接进入正题

1.vuex的安装

cnpm install vuex -S

2.然后在main.js中引入

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

3.构建核心仓库 store.js

Vuex 应用的状态 state 都应当存放在 store.js 里面,Vue 组件可以从 store.js 里面获取状态,可以把 store 通俗的理解为一个全局变量的仓库。

但是和单纯的全局变量又有一些区别,主要体现在当 store 中的状态发生改变时,相应的 vue 组件也会得到高效更新。

 在 src 目录下创建一个 vuex 目录,将 store.js 放到 vuex 目录下

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  // 定义状态
  state: {
    author: 'Wise Wrong'
  }
})

export default store

这是一个最简单的 store.js,里面只存放一个状态 author

虽然在 main.js 中已经引入了 Vue 和 Vuex,但是这里还得再引入一次,但是我自己直接在store.js里引入一次也是可以达到效果的

4.在映射到组件中

<template>
  <footer class="footer">
    <ul>
      <li v-for="lis in ul">{{lis.li}}</li>
    </ul>
    <p>
      Copyright&nbsp;&copy;&nbsp;{{author}} - 2016 All rights reserved
    </p>
  </footer>
</template>

<script>
  export default {
    name: 'footerDiv',
    data () {
      return {
        ul: [
          { li: '琉璃之金' },
          { li: '朦胧之森' },
          { li: '缥缈之滔' },
          { li: '逍遥之火' },
          { li: '璀璨之沙' }
        ]
      }
    },
    computed: {
      author () {
        return this.$store.state.author
      }
    }
  }
</script>

这是 footer.vue 的 html 和 script 部分

主要在 computed 中,将 this.$store.state.author 的值返回给 html 中的 author

页面渲染之后,就能获取到 author 的值

5.在组件中修改状态

temple

<form class="navbar-form navbar-left">
     <div class="form-group">
          <input type="text" v-model="inputTxt" class="form-control" placeholder="通过input改变author">
     </div>
     <button type="button" class="btn btn-default" @click="setAuthor">Submit</button>
</form>

script

methods:{
    setAuthor: function () {
      console.log(this.$store.state.author)
    this.$store.commit("newAuthor",this.inputTxt)
     }
  }

然后在input里输入值就可以 看到author的变化了

方法二:store.js

// 状态管理器
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
  state : {
    author: 'Wise Wrong'
  },
  mutations :{
    newAuthor(state,msg){
      state.author=msg;
    }
  },
  actions : {}
})
export default store

组件:

methods:{
    setAuthor: function () {
      console.log(this.$store.state.author)
    //    this.$store.state.author = this.inputTxt
    this.$store.commit("newAuthor",this.inputTxt)
     }
  }

一样也是可以达到改变状态的效果的

posted @ 2017-10-30 14:21  火星黑洞  阅读(213)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3