一步一步學Vue(十二)


為了提升代碼的逼格,之后代碼改為Vue文件組件,之前代碼雖然讀起來容易理解,而且適合在小的項目中使用,但是有如下缺點:

  • 全局定義(Global definitions) 強制要求每個 component 中的命名不得重復
  • 字符串模板(String templates) 缺乏語法高亮,在 HTML 有多行的時候,需要用到丑陋的 \
  • 不支持CSS(No CSS support) 意味着當 HTML 和 JavaScript 組件化時,CSS 明顯被遺漏
  • 沒有構建步驟(No build step) 限制只能使用 HTML 和 ES5 JavaScript, 而不能使用預處理器,如 Pug (formerly Jade) 和 Babel

文件擴展名為 .vue 的 single-file components(單文件組件) 為以上所有問題提供了解決方法,並且還可以使用 Webpack 或 Browserify 等構建工具。

所以基於這種考慮,我們以后會使用單文件模式去編寫代碼,並且為了看上去更洋氣一些,我們的代碼會以IView作為基礎組件,不熟悉的同學正好可以簡單了解一些,本節主要基於單文件組件重構上節的代碼。

vue官方提供了很好的命令行工具,vue-cli,可通過npm直接安裝 npm install -g vue-cli;對此我不做過多介紹,google到的內容你看都看不過來。

我們基於webpack-simple 腳手架搭建我們的項目,運行 vue init webpack-simple demo,接着一步一步走就ok了,然后進入demo 文件夾,執行npm install 安裝依賴即可,安裝完畢后執行npm run dev 即可啟動程序:

看到上述結果表示已經運行成功,從package.json的script節可以看到,開發模式下啟動了熱加載模式,無需手動刷新瀏覽器即可完成代碼重載。

既然使用IView,那么我們先安裝IView ,npm install --save iview; 並在webpack 入口頁面引入並啟用

修改我們的webpack.config.js,保證支持css引入以及字體文件導入(npm install --save-dev css-loader style-loader url-loader):

var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: 'build.js'
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
          }
          // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.css$/,
        use: ['style-loader','css-loader' ]
      },
      {
        test: /\.(gif|jpg|png|woff|svg|eot|ttf)\??.*$/,
        loader: 'url-loader?limit=1024'
      },
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    }
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

 

此時我們的iview已經可用了,我們這里引入了iview全部組件,如果按需引入,則需要對每一個組件進行分別引入。首先搭建我們布局頁(直接簡單修改iview layout代碼):

<template>
    <div class="layout" :class="{'layout-hide-text': spanLeft < 5}">
        <Row type="flex">
            <i-col :span="spanLeft" class="layout-menu-left">
                <Menu active-name="1" theme="dark" width="auto">
                    <div class="layout-logo-left">
                    Demo Project
                    </div>
                    <Menu-item name="1">
                        <Icon type="ios-navigate" :size="iconSize"></Icon>
                        <span class="layout-text">TODOList</span>
                    </Menu-item>
                   
                </Menu>
            </i-col>
            <i-col :span="spanRight">
                <div class="layout-header">
                    <i-button type="text" @click="toggleClick">
                        <Icon type="navicon" size="32"></Icon>
                    </i-button>
                </div>
               
                <div class="layout-content">
                    <div class="layout-content-main">內容區域</div>
                </div>
                <div class="layout-copy">
                    2011-2016 &copy; demo
                </div>
            </i-col>
        </Row>
    </div>
</template>
<script>
    export default {
        data () {
            return {
                spanLeft: 5,
                spanRight: 19
            }
        },
        computed: {
            iconSize () {
                return this.spanLeft === 5 ? 14 : 24;
            }
        },
        methods: {
            toggleClick () {
                if (this.spanLeft === 5) {
                    this.spanLeft = 2;
                    this.spanRight = 22;
                } else {
                    this.spanLeft = 5;
                    this.spanRight = 19;
                }
            }
        }
    }
</script>

<style scoped>
    .layout{
        border: 1px solid #d7dde4;
        background: #f5f7f9;
        position: relative;
        border-radius: 4px;
        overflow: hidden;
    }
    .layout-breadcrumb{
        padding: 10px 15px 0;
    }
    .layout-content{
        min-height: 200px;
        margin: 15px;
        overflow: hidden;
        background: #fff;
        border-radius: 4px;
    }
    .layout-content-main{
        padding: 10px;
        min-height:768px;
    }
    .layout-copy{
        text-align: center;
        padding: 10px 0 20px;
        color: #9ea7b4;
    }
    .layout-menu-left{
        background: #464c5b;
    }
    .layout-header{
        height: 60px;
        background: #fff;
        box-shadow: 0 1px 1px rgba(0,0,0,.1);
    }
    .layout-logo-left{
        width: 90%;
        height: 30px;
        background: #5b6270;
        border-radius: 3px;
        margin: 15px auto;
        text-align:center;
        line-height:30px;
        color:#fff;
    }
    .layout-ceiling-main a{
        color: #9ba7b5;
    }
    .layout-hide-text .layout-text{
        display: none;
    }
    .ivu-col{
        transition: width .2s ease-in-out;
    }
</style>

運行npm run dev:可看到如下效果:

接下來引入我們的vuex,使用npm install --save vuex ,並對main.js做如下修改:

import Vue from 'vue'
import IView from 'iview';
import Vuex from 'vuex';
import App from './App.vue'
import 'iview/dist/styles/iview.css';

import store from './store';

Vue.use(IView);
Vue.use(Vuex);




new Vue({
  el: '#app',
  store,
  render: h => h(App)
})

創建store.js,並添加如下代碼(代碼來源於上一篇博文中代碼):

var list=[];




export default {
    state: {
        items: [], // todoContainer中items,
        //初始化表單所用
        initItem: {
            title: '',
            desc: '',
            id: ''
        }
    },

    mutations: {
        search (state, payload) {
            state.items = list.filter(v => v.title.indexOf(payload.title) !== -1);
        },
        save (state, payload) {
            if (state.initItem.id) {
                var o = list.filter(v => v.id === payload.id);
                o.title = payload.title;
                o.desc = payload.desc;
                state.items = state.items.map(v => {
                    if (v.id == payload.id) {
                        return payload;
                    }
                    return v;
                });

            } else {
                var id=state.items.length+1;
                state.items.push({id:id,title:payload.title, desc:payload.desc});
            }

            list = state.items;
        },
        remove (state, payload) {
            state.items = state.items.filter(v => v.id !== payload.id);
        },
        edit (state, payload) {
            state.initItem = state.items.filter(v => v.id === payload.id)[0];
        }
    }
};

 

創建components文件夾,並按照單文件組件的規范創建組件:

SearchBar.vue

<template> 
    <div class="row toolbar">
                keyword:
                <Input type="text" v-model="keyword" ></Input>
                <Button type="primary" @click="search()">search</Button>
        </div>
</template>

<script>
export default {
    data: function () {
            return {
                keyword: ''
            }
        },
        methods: {
            search() {
                this.$store.commit("search", {
                    title: this.keyword
                });
            }
        }
}
</script>

TodoList.vue:

<template>
    <Table border :columns="columns" :data="items"></Table>
</template>
<script>
export default{
    data(){
        return {
            columns:[
                {
                    title:'Id',
                    key:'id'
                },
                {
                    title:'title',
                    key:'title',
                },
                {
                    title:'desc',
                    key:'desc'
                },
                {
                    title:'actions',
                    //TODO:操作
                
                }
            ]
        }
    },
    props:[
        'items'
    ],
    methods:{
        edit: function () {
               this.$store.commit('edit',this.todo);
            },
        remove: function () {
                this.$store.commit('remove',{id:this.todo.id});
        }
    }
}
</script>

TodoForm.vue:

<template>
  <div class="col-md-6">
        <div>
            <label for="title">title:</label>
            <input type="hidden" v-bind:value="todo.id" />
            <Input  v-model="todo.title" ></Input>
        </div>
        <div>
            <label for="desc">desc</label>
            <Input  v-model="todo.desc" ></Input>
        </div>
        <div>
            <Button type="primary" v-on:click="ok()">Ok</Button>
        </div>
    </div>
</template>
<script>
export default{
     props: ['initItem'],

        computed: {
            todo: function () {
                return { id: this.initItem.id, title: this.initItem.title, desc: this.initItem.desc };
            }
        },

        methods: {
            ok: function () {
                this.$store.commit("save",this.todo);
            }
        }
}
</script>

修改app.vue 完成組件注冊和初始化:

<template>
    <div class="layout" :class="{'layout-hide-text': spanLeft < 5}">
        <Row type="flex">
            <i-col :span="spanLeft" class="layout-menu-left">
                <Menu active-name="1" theme="dark" width="auto">
                    <div class="layout-logo-left">
                    Demo Project
                    </div>
                    <Menu-item name="1">
                        <Icon type="ios-navigate" :size="iconSize"></Icon>
                        <span class="layout-text">TODOList</span>
                    </Menu-item>
                   
                </Menu>
            </i-col>
            <i-col :span="spanRight">
                <div class="layout-header">
                    <i-button type="text" @click="toggleClick">
                        <Icon type="navicon" size="32"></Icon>
                    </i-button>
                </div>
               
                <div class="layout-content">
                    <div class="layout-content-main">
                      <search-bar></search-bar>
                      <todo-list :items="items"></todo-list>
                      <todo-form :init-item="initItem"></todo-form>
                    </div>
                </div>
                <div class="layout-copy">
                    2011-2016 &copy; demo
                </div>
            </i-col>
        </Row>
    </div>
</template>
<script>
    import SearchBar from './components/SearchBar.vue';
    import TodoForm from './components/TodoForm.vue';
    import TodoList from './components/TodoList.vue';

    export default {
        data () {
            return {
                spanLeft: 5,
                spanRight: 19
            }
        },
        components:{
          'search-bar':SearchBar,
          'todo-form':TodoForm,
          'todo-list':TodoList
        },
        computed: {
            iconSize () {
                return this.spanLeft === 5 ? 14 : 24;
            },
            initItem: function () {
                return this.$store.state.initItem;
            },
            items: function () {
                return this.$store.state.items;
            }
        },
        methods: {
            toggleClick () {
                if (this.spanLeft === 5) {
                    this.spanLeft = 2;
                    this.spanRight = 22;
                } else {
                    this.spanLeft = 5;
                    this.spanRight = 19;
                }
            }
        }
    }
</script>

<style scoped>
.....
</style>

 

此時保存,直接在瀏覽器可以看到如下效果:

 

今天時間不充足,重構就到這里,第一次使用單文件組件還是手生,代碼調試比較費時間,一步一步的來吧。下一篇繼續改造,里面包含了很多bug,大家可以試着修復或者完善一下。

good night。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM