vuex与组合式API
组合式API可以通过调用useStore
函数,来在setup
钩子函数中访问store
,这与在组件中使用选项式API访问this.$store
是等效的。
import {
useStore} from 'vuex';
export default{
setup(){
const store = useStore();
}
}
1.访问state
和getter
为了访问state
和getter
,需要创建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
要使用mutation
和action
时,只需要在setup
钩子函数中调用commit
和dispatch
函数
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
等方法进行路由的跳转,但是在vue3
的setup
函数里,并没有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>