美文网首页
vuex在项目中的使用

vuex在项目中的使用

作者: 五四青年_4e7d | 来源:发表于2021-02-06 22:03 被阅读0次
image.png

下载包:

npm install vuex --save  

安装依赖

通常和main.js平级,创建store.js文件

import Vue from 'vue'
import Vuex from 'Vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state:{
   count:0,//全局默认的值
  },
  getters:{
   
  },
  mutations:{
   

  }
})

组件中展示vuex的state数据:

展开运算符展示:

<template>
<div>
  {{count}}
  </div>
</template>
<script>
import  {mapState}  from  'vuex'
  export default {
    props: { 
    },
    computed: {
   ...mapState(['count'])
    }
  }
</script>
<style scoped>
</style>

普通展示:

<template>
  <div class="container">
    <!-- 直接访问state的数据 -->
    <span>{{$store.state.count}}</span>
  </div>
</template>
<script>
export default {
  name: "HelloWorld",
  props: {
  
  },
  data() {
    return {};
  },
  methods: {
  
  }
};
</script>

用mutation变更state中的数据(集中监控数据的变化):

import Vue from 'vue'
import Vuex from 'Vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state:{
   count:0,//全局默认的值
  },
  getters:{
   
  },
  mutations:{
    add(state){
      state.count++
    },
    addN(state,step){
      state.count += step
    },
    sub(state){
      state.count--
    },
    subN(state,step){
      state.count -= step
    }
  }
})

调用:

<template>
<div>
  {{count}}
  <button @click="btends1">加+1</button>
   <button @click="btends2">加+n</button>
    <button @click="btends3">减-1</button>
     <button @click="btends4">减-N</button>
  </div>
</template>
<script>
import  {mapState,mapMutations}  from  'vuex'
  export default {
    props: { 
    },
    computed: {
   ...mapState(['count'])
    },
    methods:{
      ...mapMutations(['sub','subN']),
      btends1(){
        this.$store.commit('add')
      },
      btends2(){
        this.$store.commit('addN',3)
      },
      btends3(){
         this.sub()
      },
      btends4(){
        this.subN(2)
      }
    }
  }
</script>
<style scoped>
</style>

相关文章

  • Vue状态管理vuex

    概述 官方网站https://vuex.vuejs.org/zh/ 项目中安装vuex Helloworld 在项...

  • vuex在项目中的使用

    一、 安装 : npm i vuex -S 二、在src中创建store文件夹,并创建index.js 三、 在m...

  • vuex在项目中的使用

    下载包: 安装依赖 通常和main.js平级,创建store.js文件 组件中展示vuex的state数据: 展开...

  • VueX 学习笔记

    学习目的 了解和熟练使用 VueX,能够在实际项目中运用。 VueX介绍 Vuex 是一个专为 Vue.js ...

  • Vuex

    vuex的作用是在vue的项目中方便与页面与页面之间值的传递。 一. 安装vuex,使用命令 二. 引入vuex ...

  • vue解决浏览器兼容性问题

    在 vue cli2 项目中使用Vuex时,ie浏览器会出现“Vuex requires a Promise po...

  • Vue

    此篇文章是介绍利用 vuex 储存用户登录时的相关信息的使用方法。 效果图: 使用方法: 相关配置文件 inde...

  • 引入vuex并访问存储在vuex中的数据

    1、在vue项目中①:使用命令yarn add vuex安装vuex插件②:新建文件命名为store.js,在文件...

  • 【Vue2】Vuex 基础使用

    本文仅为 vuex 使用方法,如有不对的地方,欢迎指正。项目使用可以直接拉到后面 vuex 实际项目中使用部分。 ...

  • Vuex

    今天在博客项目中用到了vuex,记录下vuex 的使用方法。Vuex 是一个专为 Vue.js 应用程序开发的状态...

网友评论

      本文标题:vuex在项目中的使用

      本文链接:https://www.haomeiwen.com/subject/efaotltx.html