在vue-cli中使用vue-router及vuex的例子

使用思維導(dǎo)圖總結(jié)Vue.js官方文檔(例子優(yōu)化、難點(diǎn)及易錯點(diǎn)注釋)【下】 中我們使用 vue-router及vuex時引入它們的方式是直接以<script src="xxx">的方式引入且就在一個文件中寫肥惭。但是實(shí)際開發(fā)時么伯,我們并不是這樣操作的疟暖,一般我們會使用vue-cli腳手架。但是使用vue-cli的話,我們在引入vue-router及vuex時寫法會稍有不同俐巴,這里我來舉個通俗易懂的例子(每一步都很詳細(xì)且代碼中比較重要或者難以理解的地方我都注釋出來了骨望,希望對大家有所幫助)。
安裝vue-cli步驟我就不細(xì)寫了欣舵。擎鸠。。

全局安裝 vue-cli
npm install --global vue-cli
創(chuàng)建一個基于 webpack 模板的新項(xiàng)目
vue init webpack vue-cli
安裝依賴缘圈,走你
cd vue-cli
npm install
npm run dev

一劣光、在vue-cli中使用vue-router

最終實(shí)現(xiàn)效果:點(diǎn)擊鏈接進(jìn)入相應(yīng)的路由(url)。


點(diǎn)擊鏈接進(jìn)入相應(yīng)的路由.gif

實(shí)現(xiàn)步驟:

1糟把、首先確保你安裝了vue-router

可在vue-cli根目錄中的package.json中的dependencies看有無vue-router绢涡;

2、確保vue-cli根目錄下的src中的main.js中引入了router;
//main.js
import Vue from 'vue'
import App from './App'
import router from './router'          //這里引入了router

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,       //這里掛載了router
  template: '<App/>',
  components: { App }
})
3糊饱、由于在main.js中import router了 import router from './router' 垂寥,因此我們要確保 src/router/index.js里的代碼完整且正確颠黎;
//index.js
import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'
//import xxx from  '@/components/xxx' 中的@表示src
// 因?yàn)閣ebpack.base.conf中別名這樣寫了==> alias: {'@': resolve('src')}
import Hello1 from '@/components/Hello1' //引入Hello1組件
import Hello2 from '@/components/Hello2' //引入Hello2組件
import notFind from '@/components/notFind' //引入notFind組件
Vue.use(Router) //這句別忘記了
export default new Router({
  mode:'history',  //使用history防止url中出現(xiàn)#
  routes: [
    {
      path: '/',
      name: 'Hello',
      component: Hello
    }
    ,{
      path: '/hello1',
      name: 'Hello1',
      component: Hello1
    }
    ,{
      path: '/hello2',
      name: 'Hello2',
      component: Hello2
    }
    ,{
      path: '*',
      name: 'notFind',
      component: notFind
    }

  ]
})
4另锋、由于在index.js 引入了(import)src目錄下的components 中的 Hello.vue 、Hello1.vue 狭归、Hello2.vue及 notFind.vue夭坪,因此我需要完善相應(yīng)代碼:

Hello.vue

//Hello.vue 

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  name: 'hello',
  data () {
    return {
      msg: '我是src/components里的hello.vue,我通過app.vue里的router-view展示'
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
</style>

Hello1.vue

//Hello1.vue

<template>
  <div>
  <h1>我是Hello1.vue</h1>
  </div>
</template>

<script>

export default {
    name:'Hello1',
    data:function () {
    return {}
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
</style>

Hello2.vue

//Hello2.vue
<template>
  <div>
    <qipa1-component></qipa1-component>
    <qipa2-component></qipa2-component>
  </div>
</template>

<script>
  import qipa1Component from '@/components/qipa1Component'
  //import xxx from  '@/components/xxx' 中的@表示src
  // 因?yàn)閣ebpack.base.conf中別名這樣寫了==> alias: {'@': resolve('src')}
  import qipa2Component from '@/components/qipa2Component'
export default {
components:{
  qipa1Component,
  qipa2Component
}
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
</style>

由于我們在Hello2.vue使用了兩個自定義組件qipa1-componentqipa2-component且import了相應(yīng)的組件过椎,因此我們在此也要完善這兩個組件
qipa1Component.vue

<template>
<h1>我是Hello2組件中的一朵奇葩</h1>
</template>

<!--<script>-->
<!--export default {}-->
<!--</script>-->

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
</style>

qipa2Component.vue

<template>
  <h1>我是Hello2組件中的另一朵奇葩</h1>
</template>

<!--<script>-->
  <!--export default {}-->
<!--</script>-->

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
</style>

接下來我們還為未匹配的路徑單獨(dú)寫了個組件應(yīng)對:

notFind.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  name: 'notFind',
  data () {
    return {
      msg: '對不起室梅,匹配不到對應(yīng)資源,我是notFind.vue'
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
</style>
5、修改App.vue內(nèi)容
<template>
  <div id="app">
    ![](./assets/logo.png)
    <h1>我是src/app.vue的h1</h1>
    <router-link to="/">點(diǎn)擊進(jìn)入hello首頁</router-link>
    <br>
    <router-link to="/hello1">點(diǎn)擊進(jìn)入hello1</router-link>
    <br>
    <router-link to="/hello2">點(diǎn)擊進(jìn)入hello2</router-link>
    <br>
    <router-link to="/h">點(diǎn)擊進(jìn)入不存在的路徑</router-link>
    <br>
    <router-view></router-view>
  </div>
</template>



<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

通過以上幾個步驟疚宇,就可以實(shí)現(xiàn)了最開始的效果圖啦亡鼠。接下來我們來使用vuex;

二敷待、在vue-cli中使用vuex

最終效果:通過Hello1.vue中的按鈕來改變gettersMsg數(shù)據(jù)间涵,從而使得只要用到gettersMsg的組件的數(shù)據(jù)都會相應(yīng)改變;

GIF3.gif
1榜揖、 同樣首先要確保安裝了vuex

如果未安裝勾哩,則將目錄切換至vue-cli后執(zhí)行 npm install vuex --save

2、創(chuàng)建vuex相關(guān)文件夾及文件

在src文件夾下新建store文件夾后举哟,在store文件夾下新建如下文件:
index.js思劳、mutations.js、actions.js妨猩、getters.js及rootState.js

3潜叛、修改src下的入口文件main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store/index'; //引入store

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store, //掛載store
  template: '<App/>',
  components: { App }
})
4、修改store/index.js

由于上面我們引入了store/index.js,因此接下來我們需要修改index.js文件:

import Vue from 'vue';
import Vuex from 'vuex';
import * as actions from './actions';  
 // * 表示將 './actions'模塊中的所有接口掛載到actions對象上  as 表示別名的意思
import * as mutations from './mutations';
import * as getters from './getters';
import state from './rootState';
Vue.use(Vuex)
const store = new Vuex.Store({
  state,
  getters,
  actions,
  mutations
})
export default store;
5钠导、修改mutations.js震嫉、actions.js、getters.js及rootState.js

由于上面引用了這些文件牡属,因此接下來我們來修改這些文件
rootState.js

const state = {
  msg: '我是原始數(shù)據(jù)',
}
export default state;

mutations.js

export const mutationsMsg = (state, payload) => {
  state.msg = payload.msg;
}

actions.js

export const changeMsg = ({commit}) => {
  commit({
    type: 'mutationsMsg',     //對應(yīng)mutation.js中的mutationsMsg方法
    msg: '我是修改后的數(shù)據(jù)~~~'
  });
};

getters.js

export const gettersMsg = state => state.msg;
6票堵、修改Hello.vue、Hello1.vue及App.vue

我們想通過Hello1.vue中的按鈕來改變數(shù)據(jù)逮栅,因此Hello1.vue修改后的代碼如下:

<template>
  <div>
  <h1>我是Hello1.vue</h1>
    <button @click="changeMsg">點(diǎn)我改變數(shù)據(jù)</button>
 <p>gettersMsg數(shù)據(jù)目前是: {{ gettersMsg }}</p>
  </div>
</template>

<script>
  import {mapGetters, mapActions} from 'vuex';


export default {
    name:'Hello1',
    data:function () {
    return {}
  },
  computed: {...mapGetters(['gettersMsg'])},
  //對應(yīng)getters.技術(shù)中的gettersMsg
  methods: {...mapActions(['changeMsg'])}
  //對應(yīng) Actions中changeMsg方法|| 映射this.changeMsg() 為 this.$store.dispatch('changeMsg')
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
</style>

Hello.vue用來展示數(shù)據(jù)

<template>
  <div class="hello">
    <h1>{{ gettersMsg }}</h1>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex';
  //引入mapGetters

  export default {
    name: 'hello',
    computed: {...mapGetters(['gettersMsg'])}
    //使用mapGetters 輔助函數(shù)
  }

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  h1, h2 {
    font-weight: normal;
  }

  ul {
    list-style-type: none;
    padding: 0;
  }

  li {
    display: inline-block;
    margin: 0 10px;
  }

  a {
    color: #42b983;
  }
</style>

當(dāng)然悴势,為了方便觀察數(shù)據(jù),你也可將App.vue修改下


<template>
  <div id="app">
    ![](./assets/logo.png)
    <router-link to="/">點(diǎn)擊進(jìn)入hello首頁</router-link>
    <br>
    <router-link to="/hello1">點(diǎn)擊進(jìn)入hello1</router-link>
    <br>
    <router-view></router-view>
    <p> 我是App.vue中的p措伐, gettersMsg 的值是----- {{gettersMsg}}</p>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex';
export default {
  name: 'app',
  computed:{...mapGetters(['gettersMsg'])}
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

最后特纤,我將我的vue-cli 上傳到github上了,有需要的可以看下侥加。

參考資料:
vue-cli+webpack+router+vuex---之vuex使用

*本文版權(quán)歸本人即簡書筆名:該賬戶已被查封 所有捧存,如需轉(zhuǎn)載請注明出處。謝謝!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末担败,一起剝皮案震驚了整個濱河市昔穴,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌提前,老刑警劉巖吗货,帶你破解...
    沈念sama閱讀 218,451評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異狈网,居然都是意外死亡宙搬,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,172評論 3 394
  • 文/潘曉璐 我一進(jìn)店門拓哺,熙熙樓的掌柜王于貴愁眉苦臉地迎上來勇垛,“玉大人,你說我怎么就攤上這事士鸥∠泄拢” “怎么了?”我有些...
    開封第一講書人閱讀 164,782評論 0 354
  • 文/不壞的土叔 我叫張陵础淤,是天一觀的道長崭放。 經(jīng)常有香客問我,道長鸽凶,這世上最難降的妖魔是什么币砂? 我笑而不...
    開封第一講書人閱讀 58,709評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮玻侥,結(jié)果婚禮上决摧,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好掌桩,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,733評論 6 392
  • 文/花漫 我一把揭開白布边锁。 她就那樣靜靜地躺著,像睡著了一般波岛。 火紅的嫁衣襯著肌膚如雪茅坛。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,578評論 1 305
  • 那天则拷,我揣著相機(jī)與錄音贡蓖,去河邊找鬼。 笑死煌茬,一個胖子當(dāng)著我的面吹牛斥铺,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播坛善,決...
    沈念sama閱讀 40,320評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼晾蜘,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了眠屎?” 一聲冷哼從身側(cè)響起剔交,我...
    開封第一講書人閱讀 39,241評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎组力,沒想到半個月后省容,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體抖拴,經(jīng)...
    沈念sama閱讀 45,686評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡燎字,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,878評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了阿宅。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片候衍。...
    茶點(diǎn)故事閱讀 39,992評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖洒放,靈堂內(nèi)的尸體忽然破棺而出蛉鹿,到底是詐尸還是另有隱情,我是刑警寧澤往湿,帶...
    沈念sama閱讀 35,715評論 5 346
  • 正文 年R本政府宣布妖异,位于F島的核電站,受9級特大地震影響领追,放射性物質(zhì)發(fā)生泄漏他膳。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,336評論 3 330
  • 文/蒙蒙 一绒窑、第九天 我趴在偏房一處隱蔽的房頂上張望棕孙。 院中可真熱鬧,春花似錦、人聲如沸蟀俊。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,912評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽肢预。三九已至矛洞,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間烫映,已是汗流浹背缚甩。 一陣腳步聲響...
    開封第一講書人閱讀 33,040評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留窑邦,地道東北人擅威。 一個月前我還...
    沈念sama閱讀 48,173評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像冈钦,于是被迫代替她去往敵國和親郊丛。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,947評論 2 355

推薦閱讀更多精彩內(nèi)容