友友们首先需要对vue框架有一点的了解,后端开发对于前端的框架和ui库会使用就行,直接上页面:
1.购物车页面:
- <template>
- <div>
- <h1>vuex的使用简单实现购物车h1>
- <h1>{{$store.state.user.username}}h1>
- <h1>{{user.username}}h1>
- <h1>{{mycar}}h1>
- <input type="button" value="添加购物车" @click="insertcar">
- <input type="button" value="删除购物" @click="deletecar ">
- <input type="button" value="购物车" @click="Tomar">
- <input type="button" value="清空购物车" @click="Killmycar">
- div>
- template>
- <script>
- import {mapState,mapMutations} from "vuex";
- const option = {
- computed:{
- ...mapState(['user','mycar'])
- },
- data: function () {
- return {}
- },
- methods:{
- ...mapMutations(['updatename','insert','delateorderone',"killmycar"]),
- insertcar(){
- const re={
- id:"1",
- name:"张三",
- price:"100",
- }
- this.insert(re)
- const r1={
- id:"2",
- name:"李四",
- price:"1020",
- }
- this.insert(r1)
- const r2={
- id:"3",
- name:"李四",
- price:"1020",
- }
- this.insert(r2)
- },
- deletecar(){
- this.delateorderone(1)
- },
- Tomar(){
- this.$router.push("/404")
- },
- Killmycar(){
- this.killmycar()
- }
- }
- };
- export default option
- script>
2.购物车页面
- <template>
- <div>
- <h1>获取购物车的数据h1>
- <h1>{{mycar}}h1>
- div>
- template>
- <script>
- import {mapState} from 'vuex'
- const option={
- computed:{
- ...mapState(['mycar'])
- },
- data:function (){
- return{
-
- }
- }
- }
- export default option
- script>
3.vuex的js文件
- import Vue from 'vue'
- import Vuex from 'vuex'
- import createPersistedState from 'vuex-persistedstate'
-
- Vue.use(Vuex)
- //定义全局的共享数据
- export default new Vuex.Store({
- //定义全局共享实例,可以是一个或者多个
- state: {
- user:{
- username:""
- },
- mycar:[],
- },
- getters: {
- },
- //定义修改数据的方法
- mutations: {
- updatename(state,name){
- state.user.username=name
- },
- insert(state,items){
- state.mycar.push(items)
- },
- //删除一个
- delate(state){
- state.mycar.splice(0,1)
- },
- //删除指定的元素
- delateorderone(state,id){
- for(var i=0;i
mycar.length;i++){ - if(state.mycar[i].id==id){
- state.mycar.splice(i,1);
- }
- }
- },
- //清空购物车
- killmycar(state){
- state.mycar.splice(0,1000)
- }
- },
- //定义异步操作
- actions: {
- },
- modules: {
- },
- //持久化操作
- plugins: [createPersistedState({
- storage: window.sessionStorage
- })]
- })
对于vuex在页面刷新的时候数据丢失的问题:采用的(vuex-persistedstate)的一个插件
简单的原理:就是自动将vuex中的存放的信息保存到sessionStorage中在页面刷新的时候它会去判断sessionStorage中是否有值,如果有就会自动取出这个值