助你上手Vue3全家桶之VueX4教程

1,前言

这些内容是博主在学习过程中记录下来的,有一些不重要的点就跳过了,需要时自行查询文档,4.0对比3.0,区别不大。

VueX4.0官网

2,State


语法有所调整

2.1,直接使用


import { onMounted } from 'vue'
import { useStore } from 'vuex'

export default {
	name: 'Home',
	setup() {
		const Store = useStore()
		onMounted(() => {
			console.log(Store.state.author)
		})
	}
}

2.2,结合computed


import { computed } from 'vue'
import { useStore } from 'vuex'

export default {
	name: 'Home',
	setup() {
		const Store = useStore()
		return {
      count: computed(() => Store.state.author)
    }
	}
}

3,Getter


语法有所调整

3.1,直接使用


import { onMounted } from 'vue'
import { useStore } from 'vuex'

export default {
	name: 'Home',
	setup() {
		const Store = useStore()
		onMounted(() => {
			console.log(Store.getters.getCookie)
			console.log(Store.getters.getToken('Param'))
		})
	}
}

3.2,结合computed


import { computed } from 'vue'
import { useStore } from 'vuex'

export default {
	name: 'Home',
	setup() {
		const Store = useStore()
		return {
			count1: computed(() => Store.getters.getCookie),
			count2: computed(() => Store.getters.getToken('param'))
		}
	}
}

4,Mutation


语法有所调整

4.1,直接使用


<p @click="set">{{ cookie }}</p>
import { computed } from 'vue'
import { useStore } from 'vuex'

export default {
	name: 'Home',
	setup() {
		const Store = useStore()
		const set = function() {
			Store.commit('setCookie', 'param')
		}
		return {
			set,
			cookie: computed(() => Store.state.cookie)
		}
	}
}

4.2,结合computed


<p @click="set">{{ cookie }}</p>
import { computed } from 'vue'
import { useStore } from 'vuex'

export default {
	name: 'Home',
	setup() {
		const Store = useStore()
		return {
			cookie: computed(() => Store.state.cookie),
			set: () => Store.commit('setCookie', 'param')
		}
	}
}

5,Action


语法有所调整

5.1,直接使用


<p @click="set">{{ cookie }}</p>
import { computed } from 'vue'
import { useStore } from 'vuex'

export default {
	name: 'Home',
	setup() {
		const Store = useStore()
		const set = function() {
			Store.dispatch('set', 'param')
		}
		return {
			cookie: computed(() => Store.state.cookie),
			set
		}
	}
}

5.2,结合computed


<p @click="set">{{ cookie }}</p>
import { computed } from 'vue'
import { useStore } from 'vuex'

export default {
	name: 'Home',
	setup() {
		const Store = useStore()
		return {
			cookie: computed(() => Store.state.cookie),
			set: () => Store.dispatch('set', 'param')
		}
	}
}

后记:Modules就不做赘述了,具体用法可以参考【超详细!Vuex手把手教程】


如果看了觉得有帮助的,我是@鹏多多,欢迎 点赞 关注 评论;END


PS:在本页按F12,在console中输入document.querySelectorAll('.diggit')[0].click(),有惊喜哦


面向百度编程

公众号

weixinQRcode.png

往期文章

个人主页

posted @ 2021-11-01 10:12  鹏多多  阅读(258)  评论(0编辑  收藏  举报