Vue2.0项目实战语法

vue

一、安装配置依赖

1) vue init webpack-simple 项目名称    

2) cnpm install

3 )  npm run dev

4 )  cnpm install vuex vue-router axios -D

5 )  cnpm install style-loader css-loader -D

     6 )  需要在webpack.config.js中加入

         {

        test: /\.css$/,

        loader: 'style-loader!css-loader'

         }

 7 )  

二、做vue项目流程

1) 规划组件结构 (Nav.vue、Header.vue、Home.vue)

2) 编写路由(vue-router)

3 )  编写具体每个组件的功能

 

三、项目结构

1) 在src中建立components存放组件的文件夹

2) assets存放

 

四、组件篇-comonents

1) 在src中建立components存放组件的文件夹

2) 在components中建立*.vue文件

3 )  在App.vue中导入*.vue (import NavView from './components/Nav.vue')

4 )  export default{

       components:{

           NavView

      }

     }

5) 在template中显示

         <div >

            <NavView></NavView>

         </div>

 

五、路由篇-router

1) 在需要跳转的地方,加入<router-link>

         to:路由地址,tab是会自动在a标记的上一层生成li,active-class高亮的class设置

                <router-link to='/home' tag="li" active-class="active">

                    <a href="#">首页</a>

                </router-link>

2)  在要显示的地方路由切换内容的地方放入,<router-view>

3)  在main.js中引入

          import VueRouter from 'vue-router';

          import RouterConfig from './router.config.js'  //配置router的参数文件

          Vue.use(VueRouter);

          new Vue({

             el: '#app',

              router,

              render: h => h(App)

          });

          const router = new VueRouter({

mode:'history',

 scrollBehavior:() =>({y:0}),  //切换路由的时候,内容都从顶上开始读

    routes:RouterConfig

})

4)  在src中建立一个router.config.js文件

5)  router.config.js完善里面的配置

          import Home from './components/Home.vue'

          import Follow from './components/Follow.vue'

          import Column from './components/Column.vue'

export default[

    {

        path:'/home',

        component:Home

    },

     {

        path:'/follow',

        component:Follow

    },

     {

        path:'/column',

        component:Column

    },{

        path:'/',

        redirect:'/home'       //默认跳转到首页

    },{

        path:'*',

        redirect:'/home'       //404默认页面

    }

]

 

六、vuex状态管理

1) 在src下建立store文件夹 √

2) 在store中建立index.js √

         import Vue from 'vue'

         import Vuex from 'vuex'

         Vue.use(Vuex)

         import mutations from './mutations'

         import actions from './actions'

        export default new Vuex.Store({

    modules:{

        mutations

    },

    //把actions导出去

    actions

})

3) 在main.js加入vuex的代码 √

         import Vue from 'vue'

import App from './App.vue'

import VueRouter from 'vue-router'

import RouterConfig from './router.config.js'

import store from './store/'   //默认会找到store文件的index.js

Vue.use(VueRouter)

const router = new VueRouter({

    mode:'history',

    routes:RouterConfig

})

new Vue({

  el: '#app',

  router,

  store,

  render: h => h(App)

})

4) 在store中新建一个actions.js √

 export default{

    showHeader:({commit})=>{

       //需要有types.js,但是这个项目去掉了types.js

       commit('showHeader')  //commit到了mutations里面去了

    },

    hideHeader:({commit})=>{

       //需要有types.js,但是这个项目去掉了types.js

       commit('hideHeader')  //commit到了mutations里面去了

    },

}

5) 在store中新建一个mutations.js √

import getters from './getters'

const state = {

    header:true //以上来是ture

}

const mutations = {

    showHeader(state){

       state.header = true

    },

    hideHeader(state){

       state.header = false

    }

}

export default{

    state,

    mutations,

    getters

}

6) 在store中新建一个getters.js √

         export default{

    headerShow:(state)=>{

       return state.header;

    }

}

7) 在要触发的地方,加入代码App.vue √

         <NavView v-show="'headerShow'"></NavView>

         import {mapGetters, matpActions} from 'vuex'

         computed:mapGetters([

           'headerShow'

          ]),

8) 在App.vue中的exprot中加入监听路由的变化的代码 √

         watch:{

      $route(to,from){

         if(to.path=='/user-info'){

              //通知actions,状态哪个变量应该消失了为false

              //需要发起,$store是从main.js里的store来的

              //然后需要导出到index.js里

              this.$store.dispatch('hideHeader')   //发出去之后actions.js接收

         }else{

             this.$store.dispatch('showHeader')

         }

      }

    }

 

七、数据交互篇-axios

     1 ) 在main.js进入axios

        import axios from 'axios'

        //关于axios配置

//1.配置发送请求的信息

axios.interceptors.request.use(function (config){

   store.dispatch('showLoading')

   return config;

},function(error){

   return Promise.reject(error)

})

//2.配置请求回来

axios.interceptors.response.use(function (response){

   store.dispatch('hideLoading')

   return response;

},function(error){

   return Promise.reject(error)

})

//把axios对象挂到Vue原型上

Vue.prototype.$http = axios

2) 在Home.vue中加入数据交互代码

      export default {

        data(){

            return{

                arrList:[]

            }

        },

        components:{

            BannerView

        },

        mounted(){

            //获取数据

            this.fetchDate()

        },

        methods:{

            fetchDate(){

                var _this = this;

                this.$http.get('src/data/index.data').then(function(res){

                   _this.arrList.push = res.data

                }).catch(function(err){

                    console.log('Home',err)

                })

            }

        }

    }

 

八、文章的详情页制作篇

     1 ) 在home.vue路由跳转代码中加入

           <router-link :to="'/article/'+item.id">

              <h2>{{item.title}}</h2>

              <p>{{item.detail}}</p>

           </router-link>

     2)在router.config.js中写上相应的路由配置

            {

              path:'/article/:id',

              component:Article

            }

     3)在详情页article.vue接收参数,回显数据

         data(){

          return {

              articleData:[ ]

          }

      },

      mounted(){

          var reg=/\/article\/(\d+)/;

          var id = this.$route.path.match(reg)[1];

          this.fetchData(id); //获取路由的id,放出数据交互函数

      },

      methods:{

          fetchData(id){

              var _this = this;

              this.$http.get('../src/data/article.data').then(function(res){

                 console.log(res.data[id-1])

              }).catch(function(err){

                  console.log('文章详情页',err)

              })

          }

      }

 3)解决data里有html和样式的情况

<p v-html="articleData.content"></p>

      4 ) 显示图片

         <img :src="articleData.author_face">

      5)如何处理时间戳

         建立一个文件夹为filters过滤器,在2.0就只能自己写过滤器了

         {{articleData.time | normalTime}}

          filters:{

          normalTime:function(val){

               var oDate=new Date();

               oDate.setTime(val);

               var y=oDate.getFullYear();

               var m=oDate.getMonth()+1;

               var d=oDate.getDate();

               var h=oDate.getHours();

               var mm=oDate.getMinutes();

               var s=oDate.getSeconds();

               return y+'-'+m+'-'+d+' '+h+':'+mm+':'+s;

          }

       }

         因为会有很多的过滤器,所以在filters文件夹下建立一个index.js,和normalTime.js

         index.js

         import {normalTime} from './normalTime'

module.exports = {

    normalTime

}

normalTime.js

export const normalTime=(time) =>{

    if(time){

       var oDate = new Date();

       oDate.setTime(time)

       var y =oDate.getFullYear();

       var m= oDate.getMonth()+1;

       var d = oDate.getDate();

       var h = oDate.getHours();

       var mm = oDate.getMinutes();

       var s = oDate.getSeconds();

       return y + '-' + m + '-' + d + ' ' + h + ':' + mm + ':' + s;

    }

}

在main.js中,全局引入

import filters from './filters'

 

九、过渡动画篇

 1 ) 在App.vue中,修改代码

    <transition name="slide-down">

      <router-view></router-view>

    </transition>

 2)在css中加入样式

     .slide-down-enter-active, .slide-down-leave-active {

  transition: all .4s ease;

  opacity: .7;

  transform: translate3d(0, 6rem, 0);

}

.slide-down-enter, .slide-down-leave-active {

  opacity: .1;

  transform: translate3d(0, 6rem, 0);

}

 

十、语法篇

     1 ) 在style标签中导入其他css    @import './assets/css/index.css'

       (目前同一个文件离引入两个css就报错了)

    解决他在是在main.js,用require(‘./assets/css/base.css’) 全局引用

2)

 

十一、项目注意与优化

1) 第三方库的js或者是css,最好用link和script在index.html中引入,避免打包的时候太大

2) axios是不能直接use的

3) index.html引入的连接地址需要写绝对路径

         <script src="http://localhost:8080/src/assets/js/rem.min.js"></script>

4) 返回按钮的处理

          <a href="#" onclick="window.history.go(-1)">返回</a>

     5 ) 如何在vue里使用jquery

        在main.js中加入 import $ from ‘./jquery.min.js’即可

以上是 Vue2.0项目实战语法 的全部内容, 来源链接: utcz.com/z/378583.html

回到顶部