在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使用

*本文版权归本人即简书笔名:该账户已被查封 所有,如需转载请注明出处。谢谢!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,319评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,801评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,567评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,156评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,019评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,090评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,500评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,192评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,474评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,566评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,338评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,212评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,572评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,890评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,169评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,478评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,661评论 2 335

推荐阅读更多精彩内容