vuex 简单的 state与mutations 操作(创建仓库、修改仓库、读取仓库、计算属性)

创建vuex仓库

  1. 在src下创建store目录,在目录下创建index.js文件
  2. state存放属性,mutations提供修改属性的方法
import Vue from 'vue'
import 'es6-promise/auto'
import Vuex from 'vuex'

Vue.use(Vuex)

const store=new Vuex.Store({
     //创建一个vuex的仓库

    state:{
     
      str:"hello world",
      count:"999"
    },getters:{
     
      //带参数必须是用箭头函数,注意箭头函数不能使用this
      getStr:(state)=>(iden)=>{
     
        //如果返回值==0,返回str的反转且大写的值
        let str=state.str.split('').reverse().join('');
        if(iden==0){
     
          str=str.toUpperCase();
        }
        return str;
      }
    },mutations:{
     //用来改变state中的数据的
      changestr(state){
     
        state.str="world hello";
      },increment(state,data){
     
        state.str=data.params.str;
        state.count=data.params.count;
      }
    }, strict: true
  
  });

  export default store//导出仓库
  1. 在main.js中引入store/index.js文件
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'//引入store

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
     
  el: '#app',
  router,
  store,
  components: {
      App },
  template: ''
})

组件中读取和修改vuex仓库的值

<template>
  <div class="hello">
    <!-- 直接使用this.$store.state.属性名进行访问 -->
    第一种访问方式:{
     {
      this.$store.state.str }}----{
     {
      this.$store.state.count }}<br />
    <!-- 采用辅助函数进行访问 -->
    第二种访问方式:{
     {
      str }}----{
     {
      count }}<br />
    <input type="text" v-model="bstr" /><br />
    <input type="text" v-model="bcount" /><br />
    <button @click="click()">修改</button><br>
    {
     {
     this.$store.getters.getStr(1)}}<br />
    {
     {
     this.$store.getters.getStr(0)}}
    <hr>
    <HelloWorld1></HelloWorld1>
  </div>
</template>

<script>
//vuex提供了一批辅助函数,来简化对于vuex的操作
import {
      mapState } from "vuex";
import HelloWorld1 from "./HelloWorld1"

export default {
     
  data() {
     
    return {
     
      bstr: "",
      bcount: "",
    };
  },
  components:{
     
    HelloWorld1
  },
  computed: {
     
    ...mapState(["str", "count"]),
  },
  methods: {
     
    click() {
     
      let that = this;
      this.$store.commit({
     
        type: "increment",
        //对象风格提交
        params: {
     
          str: that.bstr,
          count: that.bcount,
        },
      });
    },
  },
};
</script>

子页面

<template>
  <div>
    第一种访问方式:{
     {
      this.$store.state.str }}----{
     {
      this.$store.state.count }}<br />
  </div>
</template>>

你可能感兴趣的:(vue,java,python,vue,react,git)