詳解vuex數(shù)據(jù)傳輸?shù)膬煞N方式及this.$store undefined的解決辦法
這個問題很烏龍,但也很值得記錄一下, 原因是main.js中import store時將store的首字母寫成了大寫.
問題版本的如下所示:
import Store from './store'
我大概看了一下, vue似乎不支持在import部分包含帶首字母大寫的變量,所有import進來的對象必須要小寫,我試過把router改成Router, 發(fā)現(xiàn)路由部分也會受影響.
這種方式是典型的將vuex值及其中的方法暴露給所有的組件使用, 即將vuex視作一個"全局變量", 但vuex也可以僅提供給部分組件,即誰想用,在誰的script中import這個vuex對象.
第一種方式 - 將vuex提供給所有組件(即在main.js中注冊)
//main.js
import Vue from 'vue'
import App from './App'
import store from './store'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.config.productionTip = false
Vue.use(ElementUI)
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
//store/index.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
n:101
}
})
export default store
//view部分,即真正的可視化的部分, 這個任何一個組件都可以
<template>
<div>
{{ n }}
</div>
</template>
<script>
export default {
computed: {
n () {
return this.$store.state.n
}
}
}
</script>
第二種方式, 僅部分組件可使用vuex
//main.js - 去掉了store的聲明
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.config.productionTip = false
Vue.use(ElementUI)
new Vue({
router,
render: h => h(App)
}).$mount('#app')
//store/index.js - 這個文件和上面的一樣
//想要使用vuex數(shù)據(jù)的組件. 注意,此時$store是無效的,所以只能通過store.state.n來獲取
<template>
<div>
{{ n }}
</div>
</template>
<script>
import store from './store'
export default {
computed: {
n () {
return store.state.n
}
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Vue路由跳轉(zhuǎn)與接收參數(shù)的實現(xiàn)方式
這篇文章主要介紹了Vue路由跳轉(zhuǎn)與接收參數(shù)的實現(xiàn)方式,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04
vue 地區(qū)選擇器v-distpicker的常用功能
這篇文章主要介紹了vue 地區(qū)選擇器v-distpicker的常用功能,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07
vue3.0 CLI - 1 - npm 安裝與初始化的入門教程
這篇文章主要介紹了vue3.0 CLI - 1 - npm 安裝與初始化的入門教程,本文通過實例代碼相結(jié)合的形式,給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2018-09-09
vue-cli3 項目從搭建優(yōu)化到docker部署的方法
這篇文章主要介紹了vue-cli3 項目從搭建優(yōu)化到docker部署的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01
Vue實現(xiàn)無限輪播效果時動態(tài)綁定style失效的解決方法
最近在開發(fā)中遇到了一個新需求:列表輪播滾動,實現(xiàn)方式也有很多,比如使用第三方插件,但是由于不想依賴第三方插件,想自己實現(xiàn),于是我開始了嘗試,但是在這個過程中遇到了動態(tài)綁定style樣式不生效,所以本文介紹了Vue實現(xiàn)無限輪播效果時動態(tài)綁定style失效的解決方法2024-08-08

