Vuex与插槽的例子

143 阅读1分钟

效果: QQ截图20211229151956.png

第一步:打开电脑终端:cd 创建的文件名
第二步:再输入vue create 想要创建的文件名
第三步:选择Manually select features QQ截图20211229150332.png
第四步:选中Router和Vuex 然后回车 选中用空格 QQ截图20211229150443.png
第四部:选择2.x 然后回车 QQ截图20211229150619.png
第五部:全部选择Y——————其他正常回车
第六部:cd加创建的文件名
第七部:跑项目npm run serve

操作如下图:

stroe下面的js文件:index.js如下:
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    JIA: function (state) {
      state.count++
    },
    JIAN: function (state) {
      if (state.count > 0) state.count--
      else { return false }
    }
  },
  actions: {
  },
  modules: {
  }
})


App文件夹:
<template>
  <div id="app">
    <h1>App:{{ $store.state.count }}</h1>
    <button @click="jia">+</button>
    <button @click="jian">-</button>
    <A> </A>
  </div>
</template>

<script>
import A from "./components/A.vue";

export default {
  name: "App",
  components: {
    A,
  },
  methods: {
    jia() {
      this.$store.commit("JIA");
    },
    jian() {
      this.$store.commit("JIAN");
    },
  },
};
</script>

<style>
* {
  margin: 0;
  padding: 0;
}
#app {
  text-align: center;
  width: 100%;
  height: 100vh;
  background: pink;
  font-size: 12px;
}
#app button {
  width: 20px;
  height: 20px;
}
</style>
A.vue如下:
<template>
  <div id="A">
    <div>
      <Slots v-slot="item2">
        <h1 @click="fn(item2.item1.title, $store.state.count)">
          <span> {{ item2.item1.title }}:{{ $store.state.count }} </span>
        </h1>
      </Slots>
    </div>
  </div>
</template>

<script>
import Slots from "./slot.vue";

export default {
  name: "A",
  components: {
    Slots,
  },
  data() {
    return {
      str: "",
    };
  },
  methods: {
    fn(a, b) {
      console.log(a, b);
      alert(a + ":" + b);
      this.str = a;
      this.$bus.$emit("hand", this.str);
    },
  },
};
</script>

<style>
h1 {
  margin: 0 auto;
  display: block;
  cursor: pointer;
  width: 300px;
}
.active {
  color: salmon;
}
</style>

slot.vue如下:
<template>
  <div>
    <h1 v-for="(item, index) in arr" :key="index" :class="{ active:item.title==test}">
      <slot :item1="item"></slot>
    </h1>
  </div>
</template>

<script>
export default {
  name: "Slots",

  data() {
    return {
      arr: [{ title: "A组件" }, { title: "B组件" }, { title: "C组件" }],
      test:''
    };
  },
  created() {
    this.$bus.$on("hand", ( test) => {
      console.log(test);

      this.test = test;
    });
  },
};
</script>

<style>
</style>

路径图:具体可以自己写 QQ截图20211229151415.png