store 和 [this.]$store
- 簡單來說,如果你在根元件下注入了store那麼所有的.vue檔案裡使用就可以直接用 this.$store.xxxx
Vue官網:為了在 Vue 元件中通路 this.$store.property,你需要為 Vue 執行個體提供建立好的 store。Vuex 提供了一個從根元件向所有子元件,以 store 選項的方式“注入”該 store 的機制
//main.js
import store from './store'
new Vue({
el: '#app',
store, //根元件注入store
})
//index.vue
getData() {
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) // undefined
console.log(this.$store) // 會報錯
vue項目都在什麼時候用store.state、$store.state和this.$store.state 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