第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > vue项目都在什么时候用store.state $store.state和this.$store.state

vue项目都在什么时候用store.state $store.state和this.$store.state

时间:2023-03-30 12:13:20

相关推荐

vue项目都在什么时候用store.state $store.state和this.$store.state

store 和 [this.]$store

简单来说,如果你在根组件下注入了store那么所有的.vue文件里使用就可以直接用 this.$store.xxxx

Vue官网:为了在 Vue 组件中访问 this.$store.property,你需要为 Vue 实例提供创建好的 store。Vuex 提供了一个从根组件向所有子组件,以 store 选项的方式“注入”该 store 的机制

//main.jsimport store from './store'new Vue({el: '#app',store, //根组件注入store})

//index.vuegetData() {return {userId: this.$store.state.user.userId,......}}

而在js文件里面如果想要使用store,就必须先引入import store from '@/store’然后使用store.xxx,因为js里面是打印不出来this.$store的

// src/test.js文件import store from './store/';console.log(store)console.log(this) // undefinedconsole.log(this.$store) // 会报错

this.$store 和 $store

$store是挂载在 Vue 实例上的(即Vue.prototype),而组件也其实是一个Vue实例,在组件中可使用this访问原型上的属性<template> 拥有组件实例的上下文,可直接通过{{$store.state.XXX }}访问,等价于 script 中的 this.$store.state.XXX就把$store看成在data中return的某个变量,在下面的script中使用需要加this,在上面的template中不需要加this

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。