vue3——vuex的使用和proxy替换this的使用——基础积累

vuex与组合式API

组合式API可以通过调用useStore函数,来在setup钩子函数中访问store,这与在组件中使用选项式API访问this.$store是等效的。

import {
    
    useStore} from 'vuex';
export default{
    
    
	setup(){
    
    
		const store = useStore();
	}
}

1.访问stategetter

为了访问stategetter,需要创建computed引用以保留响应性,这与选项式API中创建计算属性等效

import {
    
    computed} from 'vue'
import {
    
    useStore} from 'vuex';
export default{
    
    
	setup(){
    
    
		const store = useStore()
		return{
    
    
			//在computed函数中访问state
			count:computed(()=>store.state.count),
			//在computed函数中访问getter
			double:computed(()=>store.getters.double)
		}
	}
}

2.访问mutation和action

要使用mutationaction时,只需要在setup钩子函数中调用commitdispatch函数

import {
    
    useStore} from 'vuex';
export default{
    
    
	setup(){
    
    
		const store = useStore()
		return{
    
    
			//使用mutation
			increment:()=>store.commit('increment'),
			//使用action
			asyncIncrement:()=>store.dispatch('asyncIncrement')
		}
	}
}

this的替代方案——vue3

vue2项目中可以使用this.$router.push等方法进行路由的跳转,但是在vue3setup函数里,并没有this这个概念,因此如何使用路由方法

//在新的vue-router里面加入了一些方法,比如这里代替this的useRouter,具体使用如下:
//引入路由函数
import {
    
    useRouter} from 'vue-router';
//使用
setup(){
    
    
	//初始化路由
	const router = useRouter();
	router.push({
    
    
		path:'/'
	})
}

在vue2中可以通过this来访问$refs,vue3中由于没有this,所以就获取不到了,但是官网中提供了方法来获取

<template>
	<h2 ref="root">姓名</h2>
</template>
<script>
//使用setup的注意事项
import {
    
    onMounted,ref} from 'vue'
export default{
    
    
	name:'test9',
	setup(){
    
    
		const root = ref(null)
		onMounted(()=>{
    
    
			console.log(root.value)
		})
		return{
    
    root}
	}
}
</script>

第二种方法,也可以通过getCurrentInstance来获取

<template>
	<h2 ref="root">姓名</h2>
</template>
<script>
//使用setup的注意事项
import {
    
    onMounted,ref,getCurrentInstance} from 'vue';
export default{
    
    
	name:'test9',
	setup(){
    
    
		const {
    
    proxy} = getCurrentInstance();
		onMounted(()=>{
    
    
			console.log(proxy.$refs.root)
		})
	}
}
</script>

关于element在vue3的使用方法,没有this.$message等方法的解决方案

<template>
	<button @click="doLogin">登录</button>
</template>
<script>
import {
    
    getCurrentInstance} from 'vue';
export default{
    
    
	name:'Test',
	setup(){
    
    
		const instance = getCurrentInstance()//vue3提供的方法,创建类似于this的实例
		const doLogin = ()=>{
    
    
			instance.proxy.$message({
    
    type:'error',text:'登录失败'})
		}
		return{
    
    doLogin}
	},
	//如果想使用this.$message,需在mounted钩子函数中,setup中没有this实例
	//但vue3.0中还是建议在setup函数中进行逻辑操作
	mounted(){
    
    
		this.$message({
    
    type:'error',text:'登录失败'})
	}
}
</script>

猜你喜欢

转载自blog.csdn.net/yehaocheng520/article/details/131984775