vue 中的 store 和 $store 的区别
时间: 2023-06-20 15:05:24 浏览: 84
在 Vue 中,store 是 Vuex 的核心概念,它是一个全局状态管理器,用于管理应用程序中的共享状态。$store 是 Vue 实例上的一个属性,它提供了对 store 对象的访问。
具体来说,store 对象包含了应用程序中的所有状态,这些状态可以通过 store.commit() 方法进行修改,也可以通过 store.dispatch() 方法进行异步操作。而 $store 属性则是在 Vue 实例中提供了对 store 对象的访问,通过 this.$store 可以直接访问 store 对象。
因此,store 和 $store 的区别在于:
1. store 是 Vuex 中的一个概念,用于管理应用程序中的共享状态,而 $store 是 Vue 实例上的一个属性,提供了对 store 对象的访问。
2. store 对象包含了应用程序中的所有状态,可以通过 commit() 方法进行修改,也可以通过 dispatch() 方法进行异步操作,而 $store 只是一个属性,直接访问 store 对象。
总的来说,store 是 Vuex 的核心概念,$store 则是 Vue 实例中访问 store 对象的一种方式。
相关问题
vue 中 this.$store
在Vue中,this.$store是用来访问Vuex状态管理库的对象。通过this.$store可以获取和修改全局的状态数据。下面是一个示例:
```javascript
// 在Vue组件中使用this.$store
export default {
computed: {
count() {
return this.$store.state.count;
}
},
methods: {
increment() {
this.$store.commit('increment');
},
decrement() {
this.$store.commit('decrement');
}
}
}
```
在上面的示例中,this.$store.state.count表示获取Vuex中的count状态值,this.$store.commit('increment')表示调用Vuex中的increment mutation来修改count的值。
需要注意的是,使用this.$store之前,需要先在Vue实例中注入Vuex插件。具体的步骤可以参考Vue官方文档中的Vuex部分。
vue3this.$store
在Vue3中,我们无法直接使用`this.$store`来获取Vuex实例,因为Vue3中的组件实例已经发生了变化。相反,我们可以使用`useStore`这个方法来获取Vuex实例。
要使用`useStore`方法,我们首先需要导入`createStore`函数并定义我们的状态、mutations、actions和getters。在示例中,我们可以看到一个名为`store.ts`的文件,其中定义了一个名为`State`的接口和一个使用`createStore`方法创建的Vuex实例。
在组件中,我们可以通过使用`inject`函数来获取之前定义的`name`属性。例如,在`HelloWorld.vue`组件的`setup`函数中,我们可以使用`inject('name')`来获取`name`属性的值,并在`onMounted`钩子函数中打印出来。
综上所述,在Vue3中,我们可以通过使用`useStore`方法和`inject`函数来获取Vuex实例和属性的值,而不再使用`this.$store`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)