Vue项目

1、新建Vue项目:vue init webpack projectName

2、vue-router模块

  1、安装vue-router模块:npm install vue-router --save-dev

  2、在src文件夹下新建文件夹router继续新建文件index.js

    编辑index.js文件

    首先引入模块:

      import Vue from 'vue';

      import VueRouter from 'vue-router';

      import home from '../component/home'

      import user from '../component/user'

      ...(引入自己定义的组件)

    声明引用:

      Vue.use(VueRouter);

    在接口通告新建的 router:

      exports default new VueRouter({

        routes: [

          {path: '/home', component: home},
          {path: '/user', component: user}...

        ]

      })

  3、在main.js中编辑

    import router from './router'(引入模块)

    

    new Vue({
        el: '#app',
        router,   //(在Vue对象中加入router)
        components: {
            App
        },
        template: '<App/>'
    })
 

  4、在App组件(组件都可以)中引用

    <router-link to="/home">home</router-link>

    <router-link to="/user">user</router-link>

    <div>

      <router-view></router-view>

    </div>

2、vuex模块

  1、安装vuex模块:npm install vuex --save

  2、在src文件夹下创建新文件夹store再创建文件index.js

    编辑index.js文件

    引入模块:

      import Vue from 'vue'

      import Vuex from 'vuex'

    声明引用:

      Vue.use(Vuex)

    宣告出口:

      export default new Vuex.Store({

        

      })

  3、在main.js中编辑

    import store from './store/index'(引入模块)

    new Vue({
        el: '#app',
        store,  //(在Vue对象中加入store)
        components: {
            App
        },
        template: '<App/>'
    })
 

  4、在index.js中继续编辑:

    1、声明变量(单一状态树)

      const state = {

        count,

        sum...(等等需要在不同组件中使用的变量)

      }

      在其他组件中引用:

        1、先引入store模块:import store from '@/store/index'

        2、正常访问变量:$store.state.count

        3、通过 computed 的计算属性直接赋值    

computed: {
  count () {
    return this.$store.state.count
  },
  sum() {
    return this.$store.state.sum
  }
}

        4、借用辅助函数mapState

<script>
  import mapState from 'vuex'//引入辅助函数
  
  computed: mapState({//ES6的箭头函数
    count: state => state.count,
    sum: state => state.sum
  })

  //或者直接使用mapState辅助函数的字符串数组
  computed: mapState(['count', 'sum'])

</script>

    2、声明控制状态对象的方法:

      const mutations = {

        add (state, n) {

          state.count += n;

        }

      }

      在其他组件中引用:

        1、正常访问:$.store.commit('add', '10')

        2、通过methods方法控制mutations(参考上面computed,注意:提交方法为:this.$store.commit('add'))

        3、借用mapMutations辅助函数  

import {mapState, mapMutations} from 'vuex'//引入辅助函数

methods: {
  ...mapMutations(['add'])
}

      

    

    

原文地址:https://www.cnblogs.com/lianchenxi/p/9440389.html