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

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

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

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

最終實現效果:點擊鏈接進入相應的路由(url)。


點擊鏈接進入相應的路由.gif

實現步驟:

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
// 因為webpack.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中出現#
  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,因此我需要完善相應代碼:

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
  // 因為webpack.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了相應的組件,因此我們在此也要完善這兩個組件
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>

接下來我們還為未匹配的路徑單獨寫了個組件應對:

notFind.vue

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

<script>
export default {
  name: 'notFind',
  data () {
    return {
      msg: '對不起,匹配不到對應資源,我是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內容
<template>
  <div id="app">
    ![](./assets/logo.png)
    <h1>我是src/app.vue的h1</h1>
    <router-link to="/">點擊進入hello首頁</router-link>
    <br>
    <router-link to="/hello1">點擊進入hello1</router-link>
    <br>
    <router-link to="/hello2">點擊進入hello2</router-link>
    <br>
    <router-link to="/h">點擊進入不存在的路徑</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>

通過以上幾個步驟,就可以實現了最開始的效果圖啦。接下來我們來使用vuex;

二、在vue-cli中使用vuex

最終效果:通過Hello1.vue中的按鈕來改變gettersMsg數據,從而使得只要用到gettersMsg的組件的數據都會相應改變;

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

如果未安裝,則將目錄切換至vue-cli后執行 npm install vuex --save

2、創建vuex相關文件夾及文件

在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: '我是原始數據',
}
export default state;

mutations.js

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

actions.js

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

getters.js

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

我們想通過Hello1.vue中的按鈕來改變數據,因此Hello1.vue修改后的代碼如下:

<template>
  <div>
  <h1>我是Hello1.vue</h1>
    <button @click="changeMsg">點我改變數據</button>
 <p>gettersMsg數據目前是: {{ gettersMsg }}</p>
  </div>
</template>

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


export default {
    name:'Hello1',
    data:function () {
    return {}
  },
  computed: {...mapGetters(['gettersMsg'])},
  //對應getters.技術中的gettersMsg
  methods: {...mapActions(['changeMsg'])}
  //對應 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用來展示數據

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

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

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

</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>

當然,為了方便觀察數據,你也可將App.vue修改下


<template>
  <div id="app">
    ![](./assets/logo.png)
    <router-link to="/">點擊進入hello首頁</router-link>
    <br>
    <router-link to="/hello1">點擊進入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使用

*本文版權歸本人即簡書筆名:該賬戶已被查封 所有,如需轉載請注明出處。謝謝!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容